コード例 #1
0
        private static IStatement CreateIfStatement()
        {
            var condition = new LessThan(new Variable<int>("x"), new Number(0));
            var consequence = new Assign<int>(new Variable<int>("a"), new Number(1));
            var alternative = new Assign<int>(new Variable<int>("b"), new Number(1));

            var ifStatement = new If(condition, consequence, alternative);
            return ifStatement;
        }
コード例 #2
0
        private static IStatement CreateWhileStatement()
        {
            // while (x < 5) { x = x + x }
            var condition = new LessThan(new Variable<int>("x"), new Number(5));
            var body = new Assign<int>(
                new Variable<int>("x"),
                new Add(new Variable<int>("x"), new Variable<int>("x")));

            var whileStatement = new While(condition, body);
            return whileStatement;
        }
コード例 #3
0
        public void GivenAnAssignmentWithIreducibleExpression_WhenReduceIsCalled_ThenTheEnvironmentIsChanged()
        {
            var environment = Environment.Empty;
            var assignment =
                new Assign<int>(
                    new Variable<int>("x"),
                    new Number(9));

            var state = assignment.Reduce(environment);

            var value = state.Environment.GetValue<int>("x");

            value.Value.Should().Be(9);
        }
コード例 #4
0
        public void GivenASequence_WhenItIsRun_BothStatementsAreExecuted()
        {
            var first = new Assign<int>(new Variable<int>("x"), new Add(new Number(1), new Number(2)));
            var second = new Assign<int>(new Variable<int>("y"), new Add(new Number(3), new Number(4)));

            var sequence = new Sequence(first, second);

            var machine = new Machine(sequence, Environment.Empty);
            machine.Run();
            var finalEnvironment = machine.Environment;

            finalEnvironment.GetValue<int>("x").Value.Should().Be(3, "the first statement was executed");
            finalEnvironment.GetValue<int>("y").Value.Should().Be(7, "the second statement was executed");
        }
コード例 #5
0
        public void GivenAReducibleStatement_WhenRunIsCalled_TheStatementIsReduced()
        {
            var environment = Environment.Empty;

            var statement = new Assign<int>(
                new Variable<int>("q"),
                new Number(1));

            var machine = new Machine(statement, environment);

            machine.Run();

            machine.Statement.IsReducible.Should().BeFalse();
        }
コード例 #6
0
        static void Main(string[] args)
        {
            var environment = Environment.Empty;
            environment = environment.AddValue("x", new Number(3));
            environment = environment.AddValue("y", new Number(4));

            var statement = new Assign<int>(
                new Variable<int>("x"),
                new Add(
                    new Variable<int>("x"),
                    new Variable<int>("y")));

            var machine = new Machine(statement, environment);

            machine.Run();
        }
コード例 #7
0
        public void GivenAnAssignmentWithReducibleExpression_WhenReduceIsCalled_ThenTheExpressionIsReduced()
        {
            var environment = Environment.Empty;
            var assignment =
                new Assign<int>(
                    new Variable<int>("x"),
                    new Add(
                        new Number(1),
                        new Number(2)));

            var state = assignment.Reduce(environment);

            state.Environment.Should().BeSameAs(environment);

            var newAssignment = (Assign<int>)state.Program;

            newAssignment.Expression.IsReducible.Should().BeFalse();
        }
コード例 #8
0
        public void GivenAComplexStatement_WhenTheMachineIsRun_TheStatementIsExecuted()
        {
            var environment = Environment.Empty;
            environment = environment.AddValue("x", new Number(3));
            environment = environment.AddValue("y", new Number(4));

            // x = x + y
            var statement = new Assign<int>(
                new Variable<int>("x"),
                new Add(
                    new Variable<int>("x"),
                    new Variable<int>("y")));

            var machine = new Machine(statement, environment);

            machine.Run();

            machine.Environment.GetValue<int>("x").Value.Should().Be(7);
        }
コード例 #9
0
        public void RemoveBusinessClientTest()
        {
            BusinessClient client = new BusinessClient();

            client.CompanyName    = "Google";
            client.PointOfContact = "Marissa Mayer";
            client.Address1       = "100 Google Way";
            client.Address2       = " ";
            client.City           = "Mountain View";
            client.State          = "CA";
            client.Zip            = "95130";
            client.Phone          = "510-234-5642";
            client.Email          = "*****@*****.**";

            Assign obj = new Assign();

            obj.RemoveBusinessClient(client);
            BusinessClient actualClient = client;

            Assert.AreEqual(client, actualClient);
        }
コード例 #10
0
        public ActionResult <string> Post([FromBody] Assign assign)
        {
            string errMess = "";

            if (assign.deviceId.Trim() == "")
            {
                errMess += "deviceId不完整";
            }
            if (assign.orderID.Length != 22)
            {
                errMess += "orderID 不完整";
            }

            //if (check_order == "")
            //{
            //    errMess += "check_order 不完整";
            //}
            AssignResult r = new AssignResult();

            if (errMess != "")
            {
                r.code = 400;
                r.Des  = errMess;
                return(Ok(r));
            }

            var result = Core.Core.ForcedOrder(assign.deviceId, assign.orderID, "1");

            if (result == "201")
            {
                r.code = 200;
            }
            else
            {
                r.code = 400;
                r.Des  = result;
            }

            return(Ok(r));
        }
コード例 #11
0
        public static ParamLessInstruction GetAssignInstructionForDatSymbolType(DatSymbolType type)
        {
            ParamLessInstruction instruction = new ParamLessInstruction();

            switch (type)
            {
            case (DatSymbolType.Int):
            {
                instruction = new Assign();
                break;
            }

            case (DatSymbolType.String):
            {
                instruction = new AssignString();     //TODO when to use AssignStringRef?
                break;
            }

            case (DatSymbolType.Func):
            {
                instruction = new AssignFunc();
                break;
            }

            case (DatSymbolType.Float):
            {
                instruction = new AssignFloat();
                break;
            }

            case (DatSymbolType.Instance):     // TODO check if it happens
            case (DatSymbolType.Class):
            {
                instruction = new AssignInstance();
                break;
            }
            }

            return(instruction);
        }
コード例 #12
0
            public override Node getNode(string[] args, Node parent)
            {
                Assign assign = null;

                if (name == "funcAssignment")
                {
                    assign          = new Assign();
                    assign.Variable = args[0];
                    FunctionRef function = new FunctionRef();
                    function.Name     = args[1];
                    assign.expression = function;
                    assign.parent     = parent;
                }
                else if (name == "assignmentExp")
                {
                    assign          = new Assign();
                    assign.Variable = args[0];
                    assign.parent   = parent;
                }
                else
                {
                    if (Utils.IsDigitsOnly(args[1]))
                    {
                        assign            = new Assign();
                        assign.Variable   = args[0];
                        assign.expression = new IntConstant(int.Parse(args[1]));
                        assign.parent     = parent;
                    }
                    else
                    {
                        assign                   = new Assign();
                        assign.Variable          = args[0];
                        assign.expression        = new IntRef(args[0]);
                        assign.expression.parent = assign;
                        assign.parent            = parent;
                    }
                }

                return(assign);
            }
コード例 #13
0
ファイル: TypeManager.cs プロジェクト: goric/tranche-net
        public void AddField(string typeName, Assign n)
        {
            var info = TypeBuilderMap[typeName];

            if (info.FieldMap.ContainsKey(n.Name))
            {
                return;
            }

            var flags = FieldAttributes.Public;

            if (Enum.GetNames(typeof(InternalTrancheTypes)).Contains(n.Name) || typeName == "Simulation")
            {
                flags |= FieldAttributes.Static;
            }

            var type = n.Qualifier == null?LookupCilType(n.InternalType) : LookupCilType(n.Qualifier.InternalType);

            var fieldBuilder = info.Builder.DefineField(n.Name, type, flags);

            info.FieldMap.Add(n.Name, fieldBuilder);
        }
コード例 #14
0
        protected override void TraverseAssign(Assign ass)
        {
            var t = ass.Rhs.Type().AssertThat(rhs_t => rhs_t == ass.Lhs.Type());

            (t.IsCudaPrimitive() || t.IsCudaVector()).AssertTrue();

            var lhs_ref = ass.Lhs as Ref;

            if (lhs_ref != null)
            {
                _ptx.ld(ass.Rhs).dup().st(lhs_ref);
            }
            else
            {
                var lhs_eval = ass.Lhs as Eval;
                if (lhs_eval != null)
                {
                    var m = lhs_eval.InvokedMethod();
                    if (m.IsArrayGetter())
                    {
                        var args = lhs_eval.InvocationArgs();
                        args.ForEach(idx => _ptx.ld(idx));
                        _ptx.ld(ass.Rhs);
                        var rhs = _ptx._stk.Pop();
                        _ptx._stk.Push(rhs);
                        _ptx.arrset(m);
                        _ptx._stk.Push(rhs);
                    }
                    else
                    {
                        throw AssertionHelper.Fail();
                    }
                }
                else
                {
                    throw AssertionHelper.Fail();
                }
            }
        }
コード例 #15
0
        public void RemoveInterpreterTest()
        {
            Interpreter terp = new Interpreter();

            terp.Name                      = "Monica Romney";
            terp.Address1                  = "100 West Ave";
            terp.Address2                  = "Apt. 110";
            terp.City                      = "Louisville";
            terp.State                     = "KY";
            terp.Zip                       = "47384";
            terp.Phone                     = "502-234-5564";
            terp.Email                     = "*****@*****.**";
            terp.YearsOfExperience         = 10;
            terp.HighestLevelCertification = "RID III";

            Assign obj = new Assign();

            obj.AddInterpreter(terp);
            Interpreter actualTerp = terp;

            Assert.AreEqual(terp, actualTerp);
        }
コード例 #16
0
 public ActionResult CreateMultiple([Bind(Include = "Id")] List <int> stdID, int tutorID, int?staffID)
 {
     for (int i = 0; i < stdID.Count; i++)
     {
         Assign assign = new Assign();
         if (ModelState.IsValid)
         {
             int index   = stdID[i];
             var student = db.Students.Where(m => m.Id == index).SingleOrDefault();
             var tutor   = db.Tutors.Where(m => m.Id == tutorID).SingleOrDefault();
             var staff   = db.Staffs.Where(m => m.Id == staffID).SingleOrDefault();
             assign.Id      = student.Id;
             assign.Student = student;
             assign.Tutor   = tutor;
             assign.Staff   = staff;
             db.Assigns.Add(assign);
             db.SaveChanges();
             Email(student.Email, tutor.Email, "Assign Notification", "You are assigned to new course");
         }
     }
     return(RedirectToAction("Index"));
 }
コード例 #17
0
        private void button3_Click(object sender, EventArgs e)
        {
            assignedUser();
            Assign assign = new Assign {
                AssignBy    = Login.userId,
                AssignTo    = id,
                Description = textBox3.Text,
                BugId       = Program.bugId
            };

            AssignDAO assignDAO = new AssignDAO();

            try
            {
                assignDAO.Insert(assign);
                MessageBox.Show("Task assigned");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
コード例 #18
0
ファイル: Sort.cs プロジェクト: ruo2012/SevenFramework
        private static void Merge_Recursive(Compare <T> compare, Get <T> get, Assign <T> set, int start, int len)
        {
            if (len > 1)
            {
                int half = len / 2;
                Sort <T> .Merge_Recursive(compare, get, set, start, half);

                Sort <T> .Merge_Recursive(compare, get, set, start + half, len - half);

                T[] sorted = new T[len];
                int i      = start;
                int j      = start + half;
                int k      = 0;
                while (i < start + half && j < start + len)
                {
                    if (compare(get(i), get(j)) == Comparison.Greater)
                    {
                        sorted[k++] = get(j++);
                    }
                    else
                    {
                        sorted[k++] = get(i++);
                    }
                }
                for (int h = 0; h < start + half - i; h++)
                {
                    sorted[k + h] = get(i + h);
                }
                for (int h = 0; h < start + len - j; h++)
                {
                    sorted[k + h] = get(j + h);
                }
                for (int h = 0; h < len; h++)
                {
                    set(start + h, sorted[0 + h]);
                }
            }
        }
コード例 #19
0
        public bool AddAssign(AssignViewModel assignviewmodel)
        {
            string empname          = "";
            int    count            = 0;
            string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd1 = new SqlCommand("select * from EmployeeDetails where Employee_ID = '" + assignviewmodel.Emp_Id + "'", con);
                SqlCommand cmd  = new SqlCommand("update warehouse set Status= 'Assigned' where Device_ID= '" + assignviewmodel.Device_Id + "'", con);

                con.Open();
                using (SqlDataReader reader = cmd1.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        count++;
                        empname = reader["Emp_Name"].ToString().Replace(" ", String.Empty);
                    }
                }
                SqlCommand cmd2 = new SqlCommand("insert into History values('" + assignviewmodel.Device_Id + "','" + assignviewmodel.Emp_Id + "','" + empname + "',GETDATE(),'01/01/1950')", con);
                if (count == 1)
                {
                    cmd.ExecuteNonQuery();
                    cmd2.ExecuteNonQuery();
                    Assign assign = new Assign();
                    assign.Emp_Id    = assignviewmodel.Emp_Id;
                    assign.Device_Id = assignviewmodel.Device_Id;
                    employeecontext.Assigns.Add(assign);
                    employeecontext.SaveChanges();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
コード例 #20
0
        public ActionResult <string> Post([FromBody] Assign assign)
        {
            string errMess = "";

            if (assign.deviceId != null && assign.deviceId.Trim() == "")
            {
                errMess += "deviceId不完整";
            }
            if (assign.orderID != null && assign.orderID.Length != 22)
            {
                errMess += "orderID 不完整";
            }
            AssignResult r = new AssignResult();

            if (errMess != "")
            {
                r.code = 400;
                r.Des  = errMess;
                //r.Des = System.Web.HttpUtility.UrlEncode(r.Des, System.Text.Encoding.GetEncoding("UTF-8"));
                return(Ok(r));
            }

            var result = Core.Core.CancelOrder(assign.deviceId, assign.orderID);

            if (result == "201")
            {
                r.code = 200;
            }
            else
            {
                r.code = 400;
                r.Des  = result;
            }

            return(Ok(r));

            //return $"CancelOrder 收到订单{assign.orderID}处理结果:" + Core.Core.CancelOrder(assign.deviceId, assign.orderID);
        }
コード例 #21
0
ファイル: SecondPass.cs プロジェクト: goric/tranche-net
        public override void VisitAssign(Assign n)
        {
            InternalType declFieldType;

            if (n.Expr != null)
            {
                declFieldType = CheckSubTree(n.Expr);
            }
            else if (n.Statement != null)
            {
                declFieldType = CheckSubTree(n.Expr);
            }
            else
            {
                declFieldType = CheckSubTree(n.Qualifier);
            }

            n.InternalType = declFieldType;

            var desc = _mgr.AddMember(n.LValue.Id, declFieldType, _currentClass);

            n.Descriptor = desc;
        }
コード例 #22
0
ファイル: Generator.cs プロジェクト: xeno-by/conflux
        protected override void TraverseAssign(Assign ass)
        {
            var t = ass.Rhs.Type().AssertThat(rhs_t => rhs_t == ass.Lhs.Type());
            (t.IsCudaPrimitive() || t.IsCudaVector()).AssertTrue();

            var lhs_ref = ass.Lhs as Ref;
            if (lhs_ref != null)
            {
                _ptx.ld(ass.Rhs).dup().st(lhs_ref);
            }
            else
            {
                var lhs_eval = ass.Lhs as Eval;
                if (lhs_eval != null)
                {
                    var m = lhs_eval.InvokedMethod();
                    if (m.IsArrayGetter())
                    {
                        var args = lhs_eval.InvocationArgs();
                        args.ForEach(idx => _ptx.ld(idx));
                        _ptx.ld(ass.Rhs);
                        var rhs = _ptx._stk.Pop();
                        _ptx._stk.Push(rhs);
                        _ptx.arrset(m);
                        _ptx._stk.Push(rhs);
                    }
                    else
                    {
                        throw AssertionHelper.Fail();
                    }
                }
                else
                {
                    throw AssertionHelper.Fail();
                }
            }
        }
コード例 #23
0
        public ActionResult Assign(int EventId)
        {
            using (MyDatabaseEntities db = new MyDatabaseEntities())
            {
                var    eve    = db.Events.Where(a => a.EventId == EventId).FirstOrDefault();
                var    user   = db.Users.Where(a => a.EmailID == HttpContext.User.Identity.Name).FirstOrDefault();
                bool   status = false;
                Assign asig   = new Assign();

                if (eve.Type == "platne")
                {
                    status = true;
                }

                asig.EmailId  = User.Identity.Name;
                asig.Name     = user.FirstName;
                asig.LastName = user.LastName;
                asig.NIP      = user.NIP;
                asig.EventId  = eve.EventId;

                ViewBag.isPlatne = status;
                return(View(asig));
            }
        }
コード例 #24
0
        private void AddMethod(string className, string methodName, Assign ass)
        {
            JSClassItem classItem = _classLookup[className] as JSClassItem;

            if (classItem == null)
            {
                // We haven't defined this type yet, do so here.
                classItem = new JSClassItem(className, className, _fileItem);
                //classItem.Icon = Properties.Resources.JSClassItem;
                _fileItem.Classes.Add(classItem);

                _classLookup.Add(className, classItem);
                _projectBrowser.AddLookup(classItem, classItem.GetID(), _invert);
            }

// TODO methods need parent method ids in their ids, e.g. Hierarchy.js is breaking

            JSMethodItem methodItem = new JSMethodItem(methodName + "()", classItem);

            //methodItem.Icon = Properties.Resources.JSMethodItem;
            methodItem.MethodInfo = ass.right;
            classItem.Methods.Add(methodItem);
            _projectBrowser.AddLookup(methodItem, methodItem.GetID(), _invert);
        }
コード例 #25
0
        void AssignStmt(out Statement assign)
        {
            Expression exp;
            Variable   var;

            assign = null;
            Expect(1);
            var = new Variable(t.val);
            if (!SymbolTable.IsInScope(t.val) && !Options.BookVersion)
            {
                errors.SemErr(t.line, t.col, string.Format("Assignment to undeclared variable '{0}'", t.val));
            }

            Expect(17);
            Token tok = t;

            Expr(out exp);
            if (!ExpectInt(exp, tok, true))
            {
                return;
            }

            assign = new Assign(var, (TypedExpression <int>)exp);
        }
コード例 #26
0
        private void SetupInternalClass(DeclarationClass n, string name)
        {
            _typeManager.AddClass(n);

            if (name.Equals(ENTRY_POINT, StringComparison.OrdinalIgnoreCase))
            {
                var methodInfo = CreateEntryPointMethod(n, name);
                _gen = methodInfo.Builder.GetILGenerator();

                foreach (var item in Enum.GetNames(typeof(InternalTrancheTypes)))
                {
                    var ident       = new Identifier(n.Location, item);
                    var instantiate = new InstantiateClass(item, new ExpressionList());
                    var assign      = new Assign(ident, instantiate)
                    {
                        InternalType = new TypeClass(item)
                    };

                    VisitAssign(assign);
                }

                _assemblyBuilder.SetEntryPoint(methodInfo.Builder);
            }
            else
            {
                var ctorInfo = CreateInternalClassCtor(n, name);
                _gen = ctorInfo.Builder.GetILGenerator();

                var baseCtor = typeof(object).GetConstructor(Type.EmptyTypes);
                _gen.Emit(OpCodes.Ldarg_0); //this.
                if (baseCtor != null)
                {
                    _gen.Emit(OpCodes.Call, baseCtor);
                }
            }
        }
コード例 #27
0
        public void RemoveDeafClientTest()
        {
            DeafClient dc = new DeafClient();

            dc.Name              = "Marc Rubin";
            dc.Gender            = "Male";
            dc.SigningPreference = "PSE";

            List <string> interpreterList = new List <string>();

            interpreterList.Add("Monica Romney");
            interpreterList.Add("Dan Flanigan");
            interpreterList.Add("Michelle Rubin");
            interpreterList.Add("Trent Clifton");

            dc.ListOFInterpreterPreference = interpreterList;

            Assign obj = new Assign();

            obj.RemoveDeafClient(dc);
            DeafClient actualDC = dc;

            Assert.AreEqual(dc, actualDC);
        }
コード例 #28
0
        public ActionResult Assign(Assign assign)
        {
            MembershipUser mu = Membership.GetUser(assign.PublisherId);

            if (mu != null)
            {
                if (Roles.IsUserInRole(mu.UserName, "editor"))
                {
                    contentManagerService.SendToReview(assign.ContentId, assign.PublisherId);
                }

                if (Roles.IsUserInRole(mu.UserName, "publisher"))
                {
                    contentManagerService.SendToPublish(assign.ContentId, assign.PublisherId);
                }

                if (Roles.IsUserInRole(mu.UserName, "author"))
                {
                    contentManagerService.SendToVerify(assign.ContentId, assign.PublisherId);
                }
            }

            return(Json(new { Success = true }));
        }
コード例 #29
0
ファイル: Parser.cs プロジェクト: FANMixco/Simple_Compiler
    private Stmt ParseStmt()
    {
        Stmt resultado;

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

        // <stmt> := print <expr>

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

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

            this.indice++;

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

            this.indice++;

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

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

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

            this.indice++;

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

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

            this.indice++;

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

            this.indice++;

            forLoop.From = this.ParseExpr();

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

            this.indice++;

            forLoop.To = this.ParseExpr();

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

            this.indice++;

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

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

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

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

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

            this.indice++;

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

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

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

        return resultado;
    }
 public void Visit(Assign assign)
 {
     Return(assign);
 }
コード例 #31
0
        public static Node SafeExpandOpAssign(this Node root, out Dictionary<Operator, Assign> out_roots)
        {
            var roots = new Dictionary<Operator, Assign>();
            var x_root = root.Transform((Operator op) =>
            {
                var opt = op.OperatorType;
                if (!opt.IsAssign()) return (Expression)op.DefaultTransform();

                Func<Expression, Expression> mk_safe_lhs = lhs =>
                {
                    var @ref = lhs as Ref;
                    if (@ref != null) return lhs;

                    var slot = lhs as Slot;
                    if (slot != null)
                    {
                        var @this = slot.This;
                        if (@this == null || @this is Ref) return lhs;
                        else
                        {
                            var ass_root = @this.DeepClone();
                            var ref_root = new Ref(new Local(null, ass_root.Type()));
                            var ass = new Assign(ref_root, ass_root);
                            roots.Add(op, ass);

                            var fld = slot as Fld;
                            if (fld != null)
                            {
                                return new Fld(fld.Field, ref_root);
                            }

                            var prop = slot as Prop;
                            if (prop != null)
                            {
                                return new Prop(prop.Property, ref_root, prop.InvokedAsVirtual);
                            }

                            throw AssertionHelper.Fail();
                        }
                    }

                    var eval = lhs as Eval;
                    var m = eval == null ? null : eval.InvokedMethod();
                    if (m != null && m.IsArrayGetter())
                    {
                        var app = eval.Callee;
                        var @this = eval.Callee.Args.First();

                        if (@this == null || @this is Ref) return lhs;
                        else
                        {
                            var ass_root = @this.DeepClone();
                            var ref_root = new Ref(new Local(null, ass_root.Type()));
                            var ass = new Assign(ref_root, ass_root);
                            roots.Add(op, ass);

                            return new Eval(new Apply(new Lambda(m), ref_root.Concat(app.Args.Skip(1))));
                        }
                    }

                    throw AssertionHelper.Fail();
                };

                var safe_lhs = mk_safe_lhs(op.Args.FirstOrDefault());
                var rhs = op.Args.SecondOrDefault() ?? new Const(1); // hack for inc/decrements
                return new Assign(safe_lhs, Operator.Create(opt.Unassign(), safe_lhs, rhs));
            }).AssertCast<Node>();

            out_roots = roots;
            return x_root;
        }
コード例 #32
0
ファイル: Program.cs プロジェクト: JasonWilkins/visitor-tk
        static string Example3()
        {
            Pirate p = new Pirate();

            StmtList sl1 = new StmtList();

            Sub joe = new Sub("joe", sl1);

            p.Add(joe);

            LocalDecl ld1 = new LocalDecl();
            ld1.type = new StringType();

            NamedReg name = new NamedReg();
            name.name = "name";
            IdList idl1 = new IdList();
            idl1.Add(name);

            ld1.id_list = idl1;

            sl1.Add(ld1);

            Assign a1 = new Assign();
            a1.lval = name;

            StringLiteral s1 = new StringLiteral();
            s1.value = " Joe!";

            a1.rval = s1;

            sl1.Add(a1);

            Assign a2 = new Assign();
            StringLiteral s2 = new StringLiteral();
            s2.value = "Hi!";

            TmpStringReg tsr0 = new TmpStringReg();
            tsr0.number = 0;

            a2.lval = tsr0;
            a2.rval = s2;

            sl1.Add(a2);

            Assign a3 = new Assign();
            TmpStringReg tsr1 = new TmpStringReg();
            tsr1.number = 1;

            BinaryCat bc1 = new BinaryCat();
            bc1.a = tsr0;
            bc1.b = name;

            a3.lval = tsr1;
            a3.rval = bc1;

            sl1.Add(a3);

            AssignCat a4 = new AssignCat();
            a4.lval = tsr1;
            StringLiteral s3 = new StringLiteral();
            s3.value = "\n";

            a4.rval = s3;

            sl1.Add(a4);

            CallStmt cs1 = new CallStmt();
            Call c1 = new Call();
            c1.func = "print";
            c1.args = tsr1;
            cs1.call = c1;
            sl1.Add(cs1);

            StringWriter sw = new StringWriter();
            PirateWriter pv = new PirateWriter(sw);

            DynamicVisitor.accept(p, pv);

            return sw.ToString();
        }
コード例 #33
0
ファイル: _ast.cs プロジェクト: rchandrashekara/main
            internal static stmt Convert(Statement stmt) {
                stmt ast;

                if (stmt is FunctionDefinition)
                    ast = new FunctionDef((FunctionDefinition)stmt);
                else if (stmt is ReturnStatement)
                    ast = new Return((ReturnStatement)stmt);
                else if (stmt is AssignmentStatement)
                    ast = new Assign((AssignmentStatement)stmt);
                else if (stmt is AugmentedAssignStatement)
                    ast = new AugAssign((AugmentedAssignStatement)stmt);
                else if (stmt is DelStatement)
                    ast = new Delete((DelStatement)stmt);
                else if (stmt is PrintStatement)
                    ast = new Print((PrintStatement)stmt);
                else if (stmt is ExpressionStatement)
                    ast = new Expr((ExpressionStatement)stmt);
                else if (stmt is ForStatement)
                    ast = new For((ForStatement)stmt);
                else if (stmt is WhileStatement)
                    ast = new While((WhileStatement)stmt);
                else if (stmt is IfStatement)
                    ast = new If((IfStatement)stmt);
                else if (stmt is WithStatement)
                    ast = new With((WithStatement)stmt);
                else if (stmt is RaiseStatement)
                    ast = new Raise((RaiseStatement)stmt);
                else if (stmt is TryStatement)
                    ast = Convert((TryStatement)stmt);
                else if (stmt is AssertStatement)
                    ast = new Assert((AssertStatement)stmt);
                else if (stmt is ImportStatement)
                    ast = new Import((ImportStatement)stmt);
                else if (stmt is FromImportStatement)
                    ast = new ImportFrom((FromImportStatement)stmt);
                else if (stmt is ExecStatement)
                    ast = new Exec((ExecStatement)stmt);
                else if (stmt is GlobalStatement)
                    ast = new Global((GlobalStatement)stmt);
                else if (stmt is ClassDefinition)
                    ast = new ClassDef((ClassDefinition)stmt);
                else if (stmt is BreakStatement)
                    ast = new Break();
                else if (stmt is ContinueStatement)
                    ast = new Continue();
                else if (stmt is EmptyStatement)
                    ast = new Pass();
                else
                    throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType());

                ast.GetSourceLocation(stmt);
                return ast;
            }
コード例 #34
0
        public static VarInfo FromAssign(Assign s, VarInfoTable t)
        {
            var r = s.Result;

            if (s.Left is null)
            {
                var v = s.Right;
                if (v is IntConst c)
                {
                    return(new VarInfo(Flag.Const, c.Num));
                }
                if (v is Var vr)
                {
                    return(t[vr.Id].Copy());
                }
                return(new VarInfo(Flag.NAC));
            }
            var v1 = s.Right;
            var v2 = s.Left;

            {
                if (v1 is IntConst c1 && v2 is IntConst c2)
                {
                    return(new VarInfo(Flag.Const, c1.Num + c2.Num));
                }
            }

            {
                if (v1 is Var vr1 && v2 is IntConst c2)
                {
                    if (t[vr1.Id].IsConst)
                    {
                        return(new VarInfo(Flag.Const, t[vr1.Id].Value.Value + c2.Num));
                    }
                    if (t[vr1.Id].IsNac)
                    {
                        return(new VarInfo(Flag.NAC));
                    }
                    if (t[vr1.Id].IsUndef)
                    {
                        return(new VarInfo(Flag.UNDEF));
                    }
                }
            }

            {
                if (v2 is Var vr1 && v1 is IntConst c2)
                {
                    if (t[vr1.Id].IsConst)
                    {
                        return(new VarInfo(Flag.Const, t[vr1.Id].Value.Value + c2.Num));
                    }
                    if (t[vr1.Id].IsNac)
                    {
                        return(new VarInfo(Flag.NAC));
                    }
                    if (t[vr1.Id].IsUndef)
                    {
                        return(new VarInfo(Flag.UNDEF));
                    }
                }
            }

            {
                if (v1 is Var vr1 && v2 is Var vr2)
                {
                    return(MergeBin(t[vr1.Id], t[vr2.Id], s.Operation));
                }
            }
            throw new Exception();
        }
コード例 #35
0
ファイル: EmitTranslator.cs プロジェクト: destinyclown/VBF
        public override AstNode VisitAssign(Assign ast)
        {
            var vi = ast.Variable.VariableInfo;

            Field f = vi as Field;

            if (f != null)
            {
                FieldInfo fi = GetClrField(f);

                //load "this"
                m_ilgen.Emit(OpCodes.Ldarg_0);

                //push value to e-stack
                Visit(ast.Value);

                m_ilgen.Emit(OpCodes.Stfld, fi);
                return ast;
            }

            //push value to e-stack
            Visit(ast.Value);

            Parameter p = vi as Parameter;

            if (p != null)
            {
                EmitSetArg(p.Index);
                return ast;
            }

            //local variable
            EmitSetLocal(vi.Index);
            return ast;
        }
コード例 #36
0
 public virtual void VisitAssign(Assign n)
 {
 }
コード例 #37
0
        // note. pattern #3:
        // <op> ref = atom op any
        // <wb> atom = ref
        // <usage> read(ref)
        // conditions:
        // 1) exactly one read of ref
        // 2) <op> comes before <wb> and <usage>
        // 3) <wb> and <usage> may be ordered arbitrarily
        // transformed into either:
        // * read(++atom), if op is an increment (use IsInc() method to test)
        // * read(--atom), if op is a decrement (use IsDec() method to test)
        // * read(atom [op=] any), otherwise
        private static bool TryMatchPattern3(DfaHelper dfa, Expression atom)
        {
            var p3_ref = atom as Ref;
            if (p3_ref == null) return false;
            var p3_usages = dfa.Usages(p3_ref);
            if (p3_usages.Count() != 3) return false;

            var p3_op = p3_usages.First() as Assign;
            if (p3_op == null) return false;
            if (!p3_op.Lhs.Equiv(p3_ref)) return false;
            var p3_bop = p3_op.Rhs as BinaryOperator;
            if (p3_bop == null) return false;
            var p3_atom = p3_bop.Lhs;
            var p3_optype = p3_bop.OperatorType;
            var p3_any = p3_bop.Rhs;
            if (!p3_atom.IsAtom()) return false;

            var p3_usage2_stmt = p3_usages.Second().Stmt();
            var p3_usage3_stmt = p3_usages.Third().Stmt();
            Expression p3_wb, p3_usage;
            var p3_wb_template = new Assign(p3_atom, p3_ref);
            if (p3_usage2_stmt.Equiv(p3_wb_template)) { p3_wb = (Expression)p3_usage2_stmt; p3_usage = (Expression)p3_usage3_stmt; }
            else if (p3_usage3_stmt.Equiv(p3_wb_template)) { p3_wb = (Expression)p3_usage3_stmt; p3_usage = (Expression)p3_usage2_stmt; }
            else return false;

            var p3_opeq = p3_atom.CreateOpPreAssign(p3_optype, p3_any);
            if (p3_opeq == null) return false;

            dfa.Remove(p3_op, p3_wb);
            dfa.ReplaceRecursive(p3_usage, p3_ref, p3_opeq);
            return true;
        }
コード例 #38
0
ファイル: CodeGen.cs プロジェクト: santosh-mnrec/Compiler
    private void GenStmt(Stmt stmt)
    {
        if (stmt is Sequence)
        {
            Sequence seq = (Sequence)stmt;
            this.GenStmt(seq.First);
            this.GenStmt(seq.Second);
        }

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

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

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

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

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

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

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

            // **test** does x equal 100? (do the test)
            this.il.MarkLabel(test);
            this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
            this.GenExpr(forLoop.To, typeof(int));
            this.il.Emit(Emit.OpCodes.Blt, body);
        }
        else
        {
            throw new System.Exception("don't know how to gen a " + stmt.GetType().Name);
        }
    }
コード例 #39
0
 protected internal override void TraverseAssign(Assign ass)
 {
     Traverse(ass.Lhs);
     Traverse(ass.Rhs);
     Types.Add(ass, Types[ass.Rhs]);
 }
コード例 #40
0
 public VarDecl(Var var, TypeNode type, Assign a)
 {
     varNode  = var;
     typeNode = type;
     assign   = a;
 }
コード例 #41
0
 public static InstanceViewModel ApplyCustomization(this InstanceViewModel instance, Assign assigns)
 {
     instance.IsHidden = assigns.IsHidden;
     instance.Alias    = assigns.Alias;
     return(instance);
 }
コード例 #42
0
 protected internal override void TraverseAssign(Assign ass)
 {
     Traverse(ass.Lhs);
     _writer.Write(" = ");
     Traverse(ass.Rhs);
 }
コード例 #43
0
        // note. pattern #4
        // <hoard> ref = atom
        // <op> atom = ref op any
        // <usage> read(ref)
        // conditions:
        // 1) exactly one read of ref
        // 2) <hoard> comes before <op> and <usage>
        // 3) <op> and <usage> may be ordered arbitrarily
        // 4) op is either an increment or a decrement
        // transformed into either:
        // * read(atom++), if op is an increment (use IsInc() method to test)
        // * read(atom--), if op is a decrement (use IsDec() method to test)
        private static bool TryMatchPattern4(DfaHelper dfa, Expression atom)
        {
            var p4_ref = atom as Ref;
            if (p4_ref == null) return false;
            var p4_usages = dfa.Usages(p4_ref);
            if (p4_usages.Count() != 3) return false;

            var p4_op = p4_usages.Select(u => u.Stmt()).OfType<Assign>().SingleOrDefault2(ass =>
            {
                var bo = ass.Rhs as BinaryOperator;
                if (bo == null) return false;
                return bo.Lhs.Equiv(p4_ref);
            });
            if (p4_op == null) return false;
            var p4_atom = p4_op.Lhs;
            if (!p4_atom.IsAtom()) return false;
            var p4_bop = p4_op.Rhs as BinaryOperator;
            if (p4_bop == null) return false;
            if (!p4_bop.Lhs.Equiv(p4_ref)) return false;
            var p4_optype = p4_bop.OperatorType;
            var p4_any = p4_bop.Rhs;

            var p4_hoard = p4_usages.First().Stmt();
            var p4_hoard_template = new Assign(p4_ref, p4_atom);
            if (!p4_hoard.Equiv(p4_hoard_template)) return false;
            var p4_usage = p4_usages.Select(u => u.Stmt()).Except(p4_op).Last();

            var p4_opeq = p4_atom.CreateOpPostAssign(p4_optype, p4_any);
            if (p4_opeq == null) return false;

            dfa.Remove(p4_hoard, p4_op);
            dfa.ReplaceRecursive(p4_usage, p4_ref, p4_opeq); 
            return true;
        }
コード例 #44
0
ファイル: MethodBodyResolver.cs プロジェクト: jiangzhen/VBF
        public override AstNode VisitAssign(Assign ast)
        {
            var variable = ResolveVariable(ast.Variable.VariableName);
            ast.Variable.VariableInfo = variable;

            Visit(ast.Value);

            if (variable == null)
            {
                //resolve failed
                return ast;
            }

            //check if assignable
            if (!variable.Type.IsAssignableFrom(ast.Value.ExpressionType))
            {
                m_errorManager.AddError(c_SE_InvalidCast, ast.Variable.VariableName.Span, ast.Value.ExpressionType.Name, variable.Type.Name);
            }

            if (variable.Type != ast.Value.ExpressionType)
            {
                var convert = new TypeConvert(ast.Value, variable.Type);
                ast.Value = convert;
            }

            return ast;
        }
コード例 #45
0
ファイル: CodeGen.cs プロジェクト: slb1988/cs143
    private void GenStmt(Stmt stmt)
    {
        if (stmt is Sequence)
        {
            Sequence seq = (Sequence)stmt;
            this.GenStmt(seq.First);
            this.GenStmt(seq.Second);
        }

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

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

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

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

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

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

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

            // **test** does x equal 100? (do the test)
            this.il.MarkLabel(test);
            this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
            this.GenExpr(forLoop.To, typeof(int));
            this.il.Emit(Emit.OpCodes.Blt, body);
        }
        else
        {
            throw new System.Exception("don't know how to gen a " + stmt.GetType().Name);
        }
    }
コード例 #46
0
ファイル: Parser.cs プロジェクト: sameerms/compiler
        private Expression ParseExpression()
        {
            Expression curExpression;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                assign._Expression = GetCurTokenAsLiteral();

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

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

            //Check for End of Program, If program has not ended yet, Recurse....
            NextToken();
            if (_index == _tokens.Count || GetCurToken().Equals("end"))
                return curExpression;
            else
                return new LinkedList(curExpression, ParseExpression());
        }
コード例 #47
0
ファイル: CodeGen.cs プロジェクト: jbolton209/GFNHacking
    private void GenStmt(Stmt stmt)
    {
        if (stmt is Sequence)
        {
            var seq = (Sequence)stmt;
            GenStmt(seq.First);
            GenStmt(seq.Second);
        }

        else if (stmt is DeclareVariable)
        {
            // declare a local
            var declare = (DeclareVariable)stmt;
            SymbolTable[declare.Ident] = _il.DeclareLocal(declare.Expr.GetType());

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

        else if (stmt is Assign)
        {
            var assign = (Assign)stmt;
            GenerateLoadToStackForExpr(assign.Expr, assign.Expr.GetType());
            GenerateStoreFromStack(assign.Ident, assign.Expr.GetType());
        }
        else if (stmt is ConsoleOut)
        {
            // the "ConsoleOut" statement is an alias for System.Console.WriteLine.
            // it uses the string case
            GenerateLoadToStackForExpr(((ConsoleOut)stmt).Expr, typeof(string));
            //Generate console.writeline
            _il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }));
        }
        else if (stmt is ReadConsoleIn)
        {
            _il.Emit(OpCodes.Call,
                typeof(Console).GetMethod("ReadLine", BindingFlags.Public | BindingFlags.Static, null,
                    new Type[] { }, null));

            Type identType = GetIdentType(stmt);

            if(identType == typeof(int))
                _il.Emit(OpCodes.Call,
                typeof(int).GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, null,
                    new[] { typeof(string) }, null));

            GenerateStoreFromStack(((ReadConsoleIn)stmt).Ident, identType);
        }
        else if (stmt is ForLoop)
        {
            // example:
            // for x = 0 to 100 up
            //    "hello";
            // end;

            // x = 0
            var forLoop = (ForLoop)stmt;
            var assign = new Assign { Ident = forLoop.Ident, Expr = forLoop.From };
            GenStmt(assign);
            // jump to the test
            var test = _il.DefineLabel();
            _il.Emit(OpCodes.Br, test);

            // statements in the body of the for loop
            var body = _il.DefineLabel();
            _il.MarkLabel(body);
            GenStmt(forLoop.Body);

            // to (increment the value of x)
            _il.Emit(OpCodes.Ldloc, SymbolTable[forLoop.Ident]);
            _il.Emit(OpCodes.Ldc_I4, 1);
            _il.Emit(forLoop.Type == ArithOp.Up ? OpCodes.Add : OpCodes.Sub);
            GenerateStoreFromStack(forLoop.Ident, typeof(int));

            // **test** does x equal 100? (do the test)
            _il.MarkLabel(test);
            _il.Emit(OpCodes.Ldloc, SymbolTable[forLoop.Ident]);
            GenerateLoadToStackForExpr(forLoop.To, typeof(int));
            _il.Emit(forLoop.Type == ArithOp.Up ? OpCodes.Blt : OpCodes.Bgt, body);
        }
        else
        {
            throw new Exception("don't know how to gen a " + stmt.GetType().Name);
        }
    }
コード例 #48
0
        protected override void TraverseAssign(Assign ass)
        {
            if (ass.Parent is Expression)
            {
                throw new NotImplementedException();
            }
            else
            {
                if (ass.Lhs is Ref)
                {
                    var sym = ((Ref)ass.Lhs).Sym;
                    if (sym.IsLocal())
                    {
                        Traverse(ass.Rhs);
                        il.stloc(locals[(Local)sym]);
                    }
                    else if (sym.IsParam())
                    {
                        throw new NotImplementedException();
                    }
                    else
                    {
                        throw AssertionHelper.Fail();
                    }
                }
                else if (ass.Lhs is Fld)
                {
                    var fld = (Fld)ass.Lhs;
                    if (fld.This != null) Traverse(fld.This);
                    Traverse(ass.Rhs);
                    il.stfld(fld.Field);
                }
                else
                {
                    var p = ass.InvokedProperty();
                    if (p != null)
                    {
                        var prop = ass.InvokedProp();
                        var setter = prop.Property.GetSetMethod(true);
                        var @this = prop.Property.IsInstance() ? prop.This.MkArray() : Seq.Empty<Expression>();
                        var args = (ass.InvocationIndexers() ?? Seq.Empty<Expression>()).Concat(ass.Rhs);
                        var style = prop.InvokedAsVirtual ? InvocationStyle.Virtual : InvocationStyle.NonVirtual;
                        var equiv = new Eval(new Apply(new Lambda(setter, style), @this.Concat(args)));
                        Traverse(equiv);
                    }
                    else
                    {
                        // todo. we've really got to consider array-getter an lvalue
                        // currently I don't have time for that
                        // but this needs to be propagated through the entire code

                        var m = ass.Lhs.InvokedMethod();
                        if (m.IsArrayGetter())
                        {
                            var setter = m.DeclaringType.ArraySetter();
                            var args = ass.Lhs.InvocationArgs().Concat(ass.Rhs);
                            var equiv = new Eval(new Apply(new Lambda(setter), args));
                            Traverse(equiv);
                        }
                        else
                        {
                            throw AssertionHelper.Fail();
                        }
                    }
                }
            }
        }
コード例 #49
0
        public async Task <IViewComponentResult> InvokeAsync(string id)
        {
            Assign assign = new Assign();

            assign.DocId = id;
            List <SelectListItem> listItem = new List <SelectListItem>();

            listItem.Add(new SelectListItem {
                Text = "申請者", Value = "申請者"
            });
            listItem.Add(new SelectListItem {
                Text = "單位主管", Value = "單位主管"
            });
            listItem.Add(new SelectListItem {
                Text = "醫工承辦", Value = "醫工承辦"
            });
            listItem.Add(new SelectListItem {
                Text = "醫工工程師", Value = "醫工工程師"
            });
            //listItem.Add(new SelectListItem { Text = "專責單位", Value = "專責單位" });
            listItem.Add(new SelectListItem {
                Text = "醫工部主管", Value = "醫工部主管"
            });

            Instrument      sdata = _db.Instruments.Find(id);
            OutsideBmedFlow of    = _db.OutsideBmedFlows.Where(f => f.DocId == id && f.Status == "?").FirstOrDefault();
            var             ur    = _userRepo.Find(uf => uf.UserName == this.User.Identity.Name).FirstOrDefault();
            var             rel   = roleManager.GetRolesForUser(ur.Id);

            //AppUser appUser = db.AppUsers.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (of != null)
            {
                assign.ClsNow = of.Cls;
                if (sdata != null)
                {
                    if (of.Cls == "醫工主管" && rel.Contains("MedMgr"))
                    {
                        listItem.Add(new SelectListItem {
                            Text = "結案", Value = "結案"
                        });
                    }
                }

                if (of.Cls == "申請人")
                {
                    listItem.Add(new SelectListItem {
                        Text = "廢除", Value = "廢除"
                    });
                }
            }
            ViewData["FlowCls"] = new SelectList(listItem, "Value", "Text", "");

            List <SelectListItem> listItem3 = new List <SelectListItem>();

            ViewData["ClsNow"] = new SelectList(listItem3, "Value", "Text", "");


            //assign.Hint = "";
            assign.FlowUid     = sdata.ToUserId;
            assign.Application = sdata.Application;
            assign.item1       = of.item1;
            assign.item2       = of.item2;
            assign.item3       = of.item3;
            assign.item4       = of.item4;
            assign.item5       = of.item5;
            assign.item6       = of.item6;
            assign.item7       = of.item7;

            assign.Hint = "申請者→申請單位主管→醫工承辦(施曉婷)→醫工部工程師→醫工部主管→結案";

            return(View(assign));
        }
コード例 #50
0
ファイル: CodeGen.cs プロジェクト: FANMixco/Simple_Compiler
    private void GenStmt(Stmt stmt)
    {
        if (stmt is Sequence)
        {
            Sequence seq = (Sequence)stmt;
            this.GenStmt(seq.First);
            this.GenStmt(seq.Second);
        }

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

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

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

        else if (stmt is ReadInt)
        {
            this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("ReadLine", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { }, null));
            this.il.Emit(Emit.OpCodes.Call, typeof(int).GetMethod("Parse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { typeof(string) }, null));
            this.Store(((ReadInt)stmt).Ident, typeof(int));
        }
        //*******************
        else if (stmt is mcIf)
        {
            mcIf mcif = (mcIf)stmt;
            //this.GenExpr(mcif.compExpr, typeof(int));
            Emit.Label Else = this.il.DefineLabel();
            Emit.Label Then = this.il.DefineLabel();
            Emit.Label Salida = this.il.DefineLabel();
            if (mcif.compExpr is CompExpr)
            {
                CompExpr compExpr = (CompExpr)mcif.compExpr;
                this.GenExpr(compExpr.Left, typeof(int));
                this.GenExpr(compExpr.Rigth, typeof(int));
                genCodComp(compExpr.Op, Then);
            }
            else
            {
                GenExpr(mcif.compExpr, typeof(string));
                this.il.Emit(Emit.OpCodes.Ldc_I4, 0);
                this.il.Emit(Emit.OpCodes.Bne_Un, Then);
            }
            if (mcif.Else != null)
                this.il.Emit(Emit.OpCodes.Br, Else);
            else
                this.il.Emit(Emit.OpCodes.Br, Salida);
            this.il.MarkLabel(Then);
            GenStmt(mcif.Then);
            this.il.Emit(Emit.OpCodes.Br, Salida);
            this.il.MarkLabel(Else);
            if (mcif.Else != null)
                GenStmt(mcif.Else);
            this.il.MarkLabel(Salida);

        }
        else if (stmt is WhileLoop)
        {
            WhileLoop whileLoop = (WhileLoop)stmt;
            Emit.Label Body = this.il.DefineLabel();
            Emit.Label Salida = this.il.DefineLabel();
            Emit.Label Cond = this.il.DefineLabel();
            this.il.MarkLabel(Cond);
            if (whileLoop.Cond is CompExpr)
            {
                CompExpr compExpr = (CompExpr)whileLoop.Cond;
                this.GenExpr(compExpr.Left, typeof(int));
                this.GenExpr(compExpr.Rigth, typeof(int));
                genCodComp(compExpr.Op, Body);
            }
            else
            {
                GenExpr(whileLoop.Cond, typeof(string));
                this.il.Emit(Emit.OpCodes.Ldc_I4, 0);
                this.il.Emit(Emit.OpCodes.Bne_Un, Body);
            }
            this.il.Emit(Emit.OpCodes.Br, Salida);
            this.il.MarkLabel(Body);
            GenStmt(whileLoop.Body);
            this.il.Emit(Emit.OpCodes.Br, Cond);
            this.il.MarkLabel(Salida);
        }
        //*******************
        else if (stmt is ForLoop)
        {
            // example:
            // for x = 0 to 100 do
            //   print "hello";
            // end;

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

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

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

            // **test** does x equal 100? (do the test)
            this.il.MarkLabel(test);
            this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
            this.GenExpr(forLoop.To, typeof(int));
            this.il.Emit(Emit.OpCodes.Blt, body);
        }
        else
        {
            throw new System.Exception("imposible generar: " + stmt.GetType().Name);
        }
    }
コード例 #51
0
ファイル: Program.cs プロジェクト: JasonWilkins/visitor-tk
        static string Example6()
        {
            AtomExprList ael1 = new AtomExprList();
            Call c1 = new Call("foo", ael1);

            CallStmt cs1 = new CallStmt(c1);

            NumLiteral n1 = new NumLiteral(3.14);
            TmpNumReg tnr0 = new TmpNumReg(0);
            Assign a1 = new Assign(tnr0, n1);

            TmpIntReg tir0 = new TmpIntReg(0);

            IntLiteral i1 = new IntLiteral(42);
            StringLiteral s1 = new StringLiteral("hi");

            AtomExprList ael2 = new AtomExprList();
            ael2.Add(tir0);
            ael2.Add(i1);
            ael2.Add(s1);

            Call c2 = new Call("bar", ael2);
            CallStmt cs2 = new CallStmt(c2);

            NamedReg a = new NamedReg("a");
            LocalDecl ld1 = new LocalDecl(new IntType(), a);

            NamedReg b = new NamedReg("b");
            LocalDecl ld2 = new LocalDecl(new NumType(), b);

            NamedReg c = new NamedReg("c");
            LocalDecl ld3 = new LocalDecl(new StringType(), c);

            TmpNumReg tnr2 = new TmpNumReg(2);
            NumLiteral n2 = new NumLiteral(2.7);
            Assign a2 = new Assign(tnr2, n2);

            StringLiteral s2 = new StringLiteral("hello yourself");
            AtomExprList ael3 = new AtomExprList();
            ael3.Add(tnr2);
            ael3.Add(s2);
            Call c3 = new Call("baz", ael3);

            RegList rl4 = new RegList();
            rl4.Add(a);
            rl4.Add(b);
            rl4.Add(c);

            Assign a3 = new Assign(rl4, c3);

            StmtList sl1 = new StmtList();
            sl1.Add(cs1);
            sl1.Add(a1);
            sl1.Add(cs2);
            sl1.Add(ld1);
            sl1.Add(ld2);
            sl1.Add(ld3);
            sl1.Add(a2);
            sl1.Add(a3);

            Sub main = new Sub("main", sl1);

            StringLiteral s3 = new StringLiteral("Foo!\n");
            Call c4 = new Call("print", s3);
            CallStmt cs3 = new CallStmt(c4);

            StmtList sl2 = new StmtList();
            sl2.Add(cs3);

            Sub foo = new Sub("foo", sl2);

            NamedReg i = new NamedReg("i");
            ParamDecl pd1 = new ParamDecl(new NumType(), i);

            NamedReg answer = new NamedReg("answer");
            ParamDecl pd2 = new ParamDecl(new IntType(), answer);

            NamedReg message = new NamedReg("message");
            ParamDecl pd3 = new ParamDecl(new StringType(), message);

            StringLiteral s4 = new StringLiteral("Bar!\n");
            Call print1 = new Call("print", s4);
            CallStmt cs4 = new CallStmt(print1);

            Call print2 = new Call("print", i);
            CallStmt cs5 = new CallStmt(print2);

            StringLiteral s5 = new StringLiteral("\n");
            Call print3 = new Call("print", s5);
            CallStmt cs6 = new CallStmt(print3);

            Call print4 = new Call("print", answer);
            CallStmt cs7 = new CallStmt(print4);

            CallStmt cs8 = new CallStmt(print3);

            Call print5 = new Call("print", message);
            CallStmt cs9 = new CallStmt(print5);

            StmtList sl3 = new StmtList();
            sl3.Add(pd1);
            sl3.Add(pd2);
            sl3.Add(pd3);
            sl3.Add(cs4);
            sl3.Add(cs5);
            sl3.Add(cs6);
            sl3.Add(cs7);
            sl3.Add(cs8);
            sl3.Add(cs9);

            Sub bar = new Sub("bar", sl3);

            NamedReg e = new NamedReg("e");
            ParamDecl pd4 = new ParamDecl(new NumType(), e);

            NamedReg msg = new NamedReg("msg");
            ParamDecl pd5 = new ParamDecl(new StringType(), msg);

            StringLiteral s6 = new StringLiteral("Baz!\n");
            Call print7 = new Call("print", s6);
            CallStmt cs10 = new CallStmt(print7);

            Call print8 = new Call("print", e);
            CallStmt cs11 = new CallStmt(print8);

            Call print9 = new Call("print", s5);
            CallStmt cs12 = new CallStmt(print9);

            Call print10 = new Call("print", msg);
            CallStmt cs13 = new CallStmt(print10);

            AtomExprList ael4 = new AtomExprList();
            ael4.Add(new IntLiteral(1000));
            ael4.Add(new NumLiteral(1.23));
            ael4.Add(new StringLiteral("hi from baz"));
            ReturnStmt rs1 = new ReturnStmt(ael4);

            StmtList sl4 = new StmtList();
            sl4.Add(pd4);
            sl4.Add(pd5);
            sl4.Add(cs10);
            sl4.Add(cs11);
            sl4.Add(cs12);
            sl4.Add(cs13);
            sl4.Add(rs1);

            Sub baz = new Sub("baz", sl4);

            Pirate p = new Pirate();
            p.Add(main);
            p.Add(foo);
            p.Add(bar);
            p.Add(baz);

            StringWriter sw = new StringWriter();
            PirateWriter pv = new PirateWriter(sw);

            DynamicVisitor.accept(p, pv);

            return sw.ToString();
        }
コード例 #52
0
 private void ReplicatePrivatelyAllocatedLocals()
 {
     foreach (var local in _allocs.Where(kvp => kvp.Value == allocPrivate).Select(kvp => kvp.Key))
     {
         var replica = new Local(local.Name + "s", local.Type.MakeArrayType(3));
         var init = new Assign(new Ref(replica), new Eval(new Apply(
             new Lambda(replica.Type.GetConstructor(3.Times(typeof(int)).ToArray())),
             new Fld(typeof(int3).GetField("Z"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true)),
             new Fld(typeof(int3).GetField("Y"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true)),
             new Fld(typeof(int3).GetField("X"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true)))));
         _replicatedLocals.Add(local, replica);
         _replicatedInits.Add(local, init);
         _needsReplication.Add(local, false);
     }
 }
コード例 #53
0
ファイル: Program.cs プロジェクト: JasonWilkins/visitor-tk
        static string Example2()
        {
            NamedReg a = new NamedReg("a");
            NamedReg b = new NamedReg("b");
            NamedReg c = new NamedReg("c");
            NamedReg det = new NamedReg("det");

            IdList rl1 = new IdList();
            rl1.Add(a);
            rl1.Add(b);
            rl1.Add(c);
            rl1.Add(det);

            LocalDecl ld1 = new LocalDecl(new NumType(), rl1);

            IntLiteral il3 = new IntLiteral(2);
            Assign a12 = new Assign(a, il3);

            IntLiteral il4 = new IntLiteral(-3);
            Assign a13 = new Assign(b, il4);

            IntLiteral il5 = new IntLiteral(-2);
            Assign a14 = new Assign(c, il5);

            UnaryNeg un1 = new UnaryNeg(b);
            TmpNumReg tnr0 = new TmpNumReg(0);
            Assign a1 = new Assign(tnr0, un1);

            TmpNumReg tnr1 = new TmpNumReg(1);
            BinaryMul bm1 = new BinaryMul(b, b);
            Assign a2 = new Assign(tnr1, bm1);

            TmpNumReg tnr2 = new TmpNumReg(2);
            IntLiteral il1 = new IntLiteral(4);
            BinaryMul bm2 = new BinaryMul(il1, a);
            Assign a3 = new Assign(tnr2, bm2);

            BinaryMul bm3 = new BinaryMul(tnr2, c);
            Assign a4 = new Assign(tnr2, bm3);

            TmpNumReg tnr3 = new TmpNumReg(3);
            IntLiteral il2 = new IntLiteral(2);
            BinaryMul bm4 = new BinaryMul(il2, a);
            Assign a5 = new Assign(tnr3, bm4);

            BinarySub bs1 = new BinarySub(tnr1, tnr2);
            Assign a6 = new Assign(det, bs1);

            TmpNumReg tnr4 = new TmpNumReg(4);
            Call sqrt = new Call("sqrt", det);
            Assign a7 = new Assign(tnr4, sqrt);

            NamedReg x1 = new NamedReg("x1");
            NamedReg x2 = new NamedReg("x2");

            IdList rl2 = new IdList();
            rl2.Add(x1);
            rl2.Add(x2);

            LocalDecl ld2 = new LocalDecl(new NumType(), rl2);

            BinaryAdd ba1 = new BinaryAdd(tnr0, tnr4);
            Assign a8 = new Assign(x1, ba1);

            BinaryDiv bd1 = new BinaryDiv(x1, tnr3);
            Assign a9 = new Assign(x1, bd1);

            BinarySub bs2 = new BinarySub(tnr0, tnr4);
            Assign a10 = new Assign(x2, bs2);

            AssignDiv a11 = new AssignDiv(x2, tnr3);

            StringLiteral s1 = new StringLiteral("Answers to ABC formula are:\n");
            Call c1 = new Call("print", s1);
            CallStmt print1 = new CallStmt(c1);

            StringLiteral s2 = new StringLiteral("x1 = ");
            Call c2 = new Call("print", s2);
            CallStmt print2 = new CallStmt(c2);

            Call c3 = new Call("print", x1);
            CallStmt print3 = new CallStmt(c3);

            StringLiteral s4 = new StringLiteral("\nx2 = ");
            Call c4 = new Call("print", s4);
            CallStmt print4 = new CallStmt(c4);

            Call c5 = new Call("print", x2);
            CallStmt print5 = new CallStmt(c5);

            StringLiteral s6 = new StringLiteral("\n");
            Call c6 = new Call("print", s6);
            CallStmt print6 = new CallStmt(c6);

            StmtList sl1 = new StmtList();
            sl1.Add(ld1);
            sl1.Add(a12);
            sl1.Add(a13);
            sl1.Add(a14);
            sl1.Add(a1);
            sl1.Add(a2);
            sl1.Add(a3);
            sl1.Add(a4);
            sl1.Add(a5);
            sl1.Add(a6);
            sl1.Add(a7);
            sl1.Add(ld2);
            sl1.Add(a8);
            sl1.Add(a9);
            sl1.Add(a10);
            sl1.Add(a11);
            sl1.Add(print1);
            sl1.Add(print2);
            sl1.Add(print3);
            sl1.Add(print4);
            sl1.Add(print5);
            sl1.Add(print6);

            Sub foo = new Sub("foo", sl1);

            Pirate p = new Pirate();
            p.Add(foo);

            StringWriter sw = new StringWriter();
            PirateWriter pv = new PirateWriter(sw);

            DynamicVisitor.accept(p, pv);

            return sw.ToString();
        }
コード例 #54
0
 protected internal virtual void TraverseAssign(Assign ass) { ass.Unsupported(); }
コード例 #55
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);
    }
コード例 #56
0
 protected internal virtual Node TransformAssign(Assign ass)
 {
     return(ass.AcceptTransformer(this, true));
 }
コード例 #57
0
        private void Interpret()
        {
            object[] operation;
            object   akkumulator;
            object   register;

            scopes = new Scopes();
            scopes.PushScope(external);
            scopes.PushScope();

            int startTime = Environment.TickCount;

            Cancel  = false;
            running = true;

            pc = 0;

            bool accepted;
            // bool continues;
            object xPos;
            object defaultRenamed;
            object yPos;


            while ((pc < code.Count - 1) & running)
            {
                akkumulator = null;
                register    = null;

                operation = (Object[])code[pc];

                switch ((Opcodes)operation.GetValue(0))
                {
                // Konstante allozieren
                case Opcodes.opAllocConst:
                {
                    // Parameter:    Name der Konstanten; Wert
                    scopes.Allocate(operation.GetValue(1).ToString(), operation.GetValue(2).ToString(), Identifier.IdentifierTypes.idConst);
                    break;
                }

                // Variable allozieren
                case Opcodes.opAllocVar:
                {
                    // Parameter:    Name der Variablen
                    scopes.Allocate(operation.GetValue(1).ToString());
                    break;
                }

                // Wert auf den Stack schieben
                case Opcodes.opPushValue:
                {
                    // Parameter:    Wert
                    scopes.Push(operation.GetValue(1));
                    break;
                }

                // Wert einer Variablen auf den Stack schieben
                case Opcodes.opPushVariable:
                {
                    // Parameter:    Variablenname
                    string name;
                    try
                    {
                        var tmp = operation.GetValue(1);
                        if (tmp.GetType() == typeof(Identifier))
                        {
                            name = ((Identifier)tmp).value.ToString();
                        }
                        else
                        {
                            name = tmp.ToString();
                        }
                        register = scopes.Retrieve(name);
                    }
                    catch (Exception)
                    {
                        // Variable nicht alloziert, also bei Host nachfragen
                        accepted = false;
                        Retrieve?.Invoke(operation.GetValue(1).ToString(), register.ToString(), accepted);
                        if (!accepted)
                        {
                            // der Host weiss nichts von der Var. Implizit anlegen tun wir
                            // sie aber nicht, da sie hier auf sie sofort lesend zugegriffen
                            // würde

                            running = false;
                            ErrorObject.Raise((int)InterpreterError.runErrors.errUnknownVar, "Code.Run", "Unknown variable '" + operation.GetValue(1) + "'", 0, 0, 0);
                        }
                    }

                    if (register == null)
                    {
                        running = false;
                        ErrorObject.Raise((int)InterpreterError.runErrors.errUninitializedVar, "Code.Run", "Variable '" + operation.GetValue(1) + "' not hasn´t been assigned a Value yet", 0, 0, 0);
                    }
                    else
                    {
                        if (register.GetType() == typeof(Identifier))
                        {
                            scopes.Push(((Identifier)register).value);
                        }
                        else
                        {
                            scopes.Push(register.ToString());
                        }
                    }

                    break;
                }

                // entfernt obersten Wert vom Stack
                case Opcodes.opPop:
                {
                    scopes.PopScopes();
                    break;
                }

                // legt den n-ten Stackwert zuoberst auf den Stack
                case Opcodes.opPopWithIndex:
                {
                    // Parameter:    Index in den Stack (von oben an gezählt: 0..n)
                    object result;
                    register = scopes.Pop(Convert.ToInt32(operation.GetValue(1)));
                    if (register is Identifier)
                    {
                        result = ((Identifier)register).value;
                    }
                    else
                    {
                        result = register;
                    }
                    scopes.Push(result);
                    break;
                }

                // Wert auf dem Stack einer Variablen zuweisen
                case Opcodes.opAssign:
                {
                    // Parameter:    Variablenname
                    // Stack:        der zuzuweisende Wert

                    object result;
                    register = scopes.Pop();
                    if (register is Identifier)
                    {
                        result = ((Identifier)register).value;
                    }
                    else
                    {
                        result = register;
                    }
                    if (!scopes.Assign(operation.GetValue(1).ToString(), result))
                    {
                        ;
                    }
                    {
                        // Variable nicht alloziert, also Host anbieten
                        accepted = false;


                        Assign?.Invoke(operation.GetValue(1).ToString(), result.ToString(), ref accepted);
                        if (!accepted)
                        {
                            // Host hat nicht mit Var am Hut, dann legen wir
                            // sie eben selbst an
                            scopes.Allocate(operation.GetValue(1).ToString(), result.ToString());
                        }
                    }

                    break;
                }

                case Opcodes.opAdd:
                case Opcodes.opSub:
                case Opcodes.opMultiplication:
                case Opcodes.opDivision:
                case Opcodes.opDiv:
                case Opcodes.opMod:
                case Opcodes.opPower:
                case Opcodes.opStringConcat:
                case Opcodes.opOr:
                case Opcodes.opAnd:
                case Opcodes.opEq:
                case Opcodes.opNotEq:
                case Opcodes.oplt:
                case Opcodes.opLEq:
                case Opcodes.opGt:
                case Opcodes.opGEq:
                    BinaryMathOperators(operation, akkumulator, register);
                    break;

                case Opcodes.opNegate:
                case Opcodes.opNot:
                case Opcodes.opFactorial:
                case Opcodes.opSin:
                case Opcodes.opCos:
                case Opcodes.opTan:
                case Opcodes.opATan:
                    UnaryMathOperators(operation);
                    break;

                case Opcodes.opDebugPrint:
                {
                    string msg = string.Empty;


                    register = scopes.PopScopes();
                    if (register != null)
                    {
                        msg = ((Identifier)register).value.ToString();
                    }

                    DebugPrint?.Invoke(msg);


                    break;
                }

                case Opcodes.opDebugClear:
                {
                    DebugClear?.Invoke();
                    break;
                }

                case Opcodes.opDebugShow:
                {
                    DebugShow?.Invoke();
                    break;
                }

                case Opcodes.opDebugHide:
                {
                    DebugHide?.Invoke();
                    break;
                }

                case Opcodes.opMessage:
                {
                    try
                    {
                        string msg  = string.Empty;
                        int    type = 0;
                        register    = scopes.PopScopes();       // Message
                        akkumulator = scopes.PopScopes().value; // Type
                        if (register is Identifier)
                        {
                            if (register != null)
                            {
                                if (register.GetType() == typeof(Identifier))
                                {
                                    msg = ((Identifier)register).value.ToString();
                                }
                                else
                                {
                                    msg = register.ToString();
                                }
                            }
                        }


                        if (akkumulator != null)
                        {
                            if (akkumulator.GetType() == typeof(Identifier))
                            {
                                type = Convert.ToInt32(((Identifier)akkumulator).value);
                            }
                            else
                            {
                                type = Convert.ToInt32(akkumulator);
                            }
                        }


                        Message?.Invoke(type, msg);
                    }
                    catch (Exception)
                    {
                        Message?.Invoke(-1, string.Empty);
                    }

                    break;
                }

                case Opcodes.opMsgbox:
                {
                    if (!AllowUi)
                    {
                        running = false;
                        ErrorObject.Raise((int)InterpreterError.runErrors.errNoUIallowed, "Code.Run", "MsgBox-Statement cannot be executed when no UI-elements are allowed", 0, 0, 0);
                    }

                    register    = scopes.PopScopes().value; // Title
                    akkumulator = scopes.PopScopes().value; // Buttons

                    try
                    {
                        // TODO:InputBox  // scopes.Push(MsgBox(scopes.Pop, (MsgBoxStyle)Akkumulator.ToString(), Register));
                    }
                    catch (Exception ex)
                    {
                        running = false;
                        ErrorObject.Raise((int)InterpreterError.runErrors.errMath, "Code.Run", "Error during MsgBox-call: " + ex.HResult + " (" + ex.Message + ")", 0, 0, 0);
                    }

                    break;
                }

                case Opcodes.opDoEvents:
                {
                    break;
                }

                case Opcodes.opInputbox:
                {
                    if (!AllowUi)
                    {
                        running = false;
                        ErrorObject.Raise((int)InterpreterError.runErrors.errNoUIallowed, "Code.Run", "Inputbox-Statement cannot be executed when no UI-elements are allowed", 0, 0, 0);
                    }

                    yPos           = scopes.PopScopes().value;
                    xPos           = scopes.PopScopes().value;
                    defaultRenamed = scopes.PopScopes().value;
                    register       = scopes.PopScopes().value;
                    akkumulator    = scopes.PopScopes().value;

                    try
                    {
                        // TODO:InputBox
                        //string Anwert = Microsoft.VisualBasic.Interaction.InputBox(Akkumulator.ToString(), Register.ToString(), defaultRenamed.ToString(), Convert.ToInt32(xPos), Convert.ToInt32(yPos));
                        //scopes.Push(Anwert);
                    }
                    catch (Exception ex)
                    {
                        running = false;
                        ErrorObject.Raise((int)InterpreterError.runErrors.errMath, "Code.Run", "Error during MsgBox-call: " + ex.HResult + " (" + ex.Message + ")", 0, 0, 0);
                    }

                    break;
                }

                case Opcodes.opJump:
                {
                    pc = Convert.ToInt32(operation.GetValue(1)) - 1;
                    break;
                }

                case Opcodes.opJumpTrue:
                {
                    akkumulator = scopes.PopScopes().value;
                    if (Convert.ToBoolean(akkumulator))
                    {
                        pc = Convert.ToInt32(operation.GetValue(1)) - 1;
                    }
                    break;
                }

                case Opcodes.opJumpFalse:
                {
                    akkumulator = scopes.PopScopes().value;
                    if (!Convert.ToBoolean(akkumulator))
                    {
                        pc = Convert.ToInt32(operation.GetValue(1)) - 1;
                    }
                    break;
                }

                case Opcodes.opJumpPop:
                {
                    pc = Convert.ToInt32(scopes.PopScopes().value) - 1;
                    break;
                }

                case Opcodes.opPushScope:
                {
                    scopes.PushScope();
                    break;
                }

                case Opcodes.opPopScope:
                {
                    scopes.PopScopes();
                    break;
                }

                case Opcodes.opCall:
                {
                    scopes.Allocate("~RETURNADDR", (pc + 1).ToString(), Identifier.IdentifierTypes.idConst);
                    pc = Convert.ToInt32(operation.GetValue(1)) - 1;
                    break;
                }

                case Opcodes.opReturn:
                {
                    pc = Convert.ToInt32(Convert.ToDouble(scopes.Retrieve("~RETURNADDR").value, CultureInfo.InvariantCulture) - 1);
                    break;
                }
                }


                pc = pc + 1; // zum nächsten Befehl

                // wurde Interpretation unterbrochen?
                if (Cancel)
                {
                    running = false;
                    ErrorObject.Raise((int)InterpreterError.runErrors.errCancelled, "Code.Run", "Code execution aborted", 0, 0, 0);
                }

                // Timeout erreicht?
                var tickPassed = (Environment.TickCount - startTime);
                if (CodeTimeout > 0 && tickPassed >= CodeTimeout)
                {
                    running = false;
                    ErrorObject.Raise((int)InterpreterError.runErrors.errTimedOut, "Code.Run", "Timeout reached: code execution has been aborted", 0, 0, 0);
                }
            }

            running = false;
        }
コード例 #58
0
 protected internal override Node TransformAssign(Assign ass)
 {
     return Dispatch(ass);
 }
コード例 #59
0
 public VarDecl(Var v, TypeNode t)
 {
     varNode  = v;
     typeNode = t;
     assign   = null;
 }
コード例 #60
0
 protected internal override void TraverseAssign(Assign ass)
 {
     Dispatch(ass);
 }