示例#1
0
            public override Stm ProcessEntryExit1(Stm body)
            {
                Temp.Temp newTemp;
                for (int i = 0; i < 8; ++i)
                {
                    newTemp = new Temp.Temp();
                    body    = new SEQ(new MOVE(new TEMP(newTemp), new TEMP(Reg[16 + i])), body);
                    body    = new SEQ(body, new MOVE(new TEMP(Reg[16 + i]), new TEMP(newTemp)));
                }
                newTemp = new Temp.Temp();
                body    = new SEQ(new MOVE(new TEMP(newTemp), new TEMP(Reg[31])), body);
                body    = new SEQ(body, new MOVE(new TEMP(Reg[31]), new TEMP(newTemp)));

                int count = 0;

                for (AccessList ptr = Formals; ptr != null; ptr = ptr.Tail)
                {
                    if (ptr.Head is InReg)
                    {
                        body = new SEQ(new MOVE(ptr.Head.Exp(null), new TEMP(A(count))), body);
                        ++count;
                    }
                }
                for (; count < 4; count++)
                {
                    body = new SEQ(new MOVE(new TEMP(new Temp.Temp()), new TEMP(A(count))), body);
                }
                return(body);
            }
示例#2
0
 void PrintStm(Stm s, int d)
 {
     if (s is SEQ)
     {
         PrintStm((SEQ)s, d);
     }
     else if (s is LABEL)
     {
         PrintStm((LABEL)s, d);
     }
     else if (s is JUMP)
     {
         PrintStm((JUMP)s, d);
     }
     else if (s is CJUMP)
     {
         PrintStm((CJUMP)s, d);
     }
     else if (s is MOVE)
     {
         PrintStm((MOVE)s, d);
     }
     else if (s is EXP)
     {
         PrintStm((EXP)s, d);
     }
     else
     {
         throw new FatalError("Print.PrintStm");
     }
 }
示例#3
0
 private void WriteToStm <T>(StmObject <T> stm, T newValue)
 {
     using (Stm.BeginTransaction())
     {
         stm.Write(newValue);
     }
 }
示例#4
0
 private void ReadFromStm <T>(StmObject <T> stm)
 {
     using (Stm.BeginTransaction())
     {
         stm.Read();
     }
 }
        public void TestTransactionConflict()
        {
            Stm.Init();
            File.WriteAllText(logFileName, string.Empty);
            var variable_1 = new StmMemory <int>();
            var variable_2 = new StmMemory <int>();

            File.WriteAllText("Log.txt", string.Empty);
            List <Action> actions = new List <Action>()
            {
                new Action(() => {
                    Stm.Do(new TransactionalAction((IStmTransaction transaction) => {
                        variable_1.Set(2, transaction);
                        variable_1.Version[0] = 15;
                        variable_2.Set(3, transaction);
                    }), false);
                }),
            };
            List <Task> tasks = new List <Task>();

            foreach (Action action in actions)
            {
                tasks.Add(Task.Run(action));
            }
            foreach (Task task in tasks)
            {
                task.Wait();
            }
            string[] logFileLines = File.ReadAllLines("Log.txt");
            string   lastLogLine  = logFileLines[logFileLines.Length - 2];

            Assert.AreEqual(true, lastLogLine.Contains(I_STM_TRANSACTION_STATE.CONFLICT.ToString()));
        }
        public void ToCodeDomFull(StatementCollection sts)
        {
            // create enumrator and initialize it
            sts.Add(Stm.Comment("<foreach>"));
            sts.Add(Stm.Comment("This loop mimics a foreach call. See C# programming language, pg 247"));
            sts.Add(Stm.Comment("Here, the enumerator is seale and does not implement IDisposable"));
            VariableDeclarationStatement enDecl = Stm.Var(
                typeof(IEnumerator),
                "enumerator",
                this.Collection.Method("GetEnumerator").Invoke()
                );

            sts.Add(enDecl);

            // get expression
            VariableReferenceExpression en = Expr.Var(enDecl);

            // iterate
            IterationStatement iter = Stm.While(en.Method("MoveNext").Invoke());

            sts.Add(iter);
            // get local parameter
            VariableDeclarationStatement localDecl = Stm.Var(
                this.LocalType,
                this.LocalName
                );

            localDecl.InitExpression = (en.Prop("Current")).Cast(this.LocalType);
            iter.Statements.Add(localDecl);

            // add statements
            iter.Statements.Add(Stm.Comment("foreach body"));
            iter.Statements.AddRange(this.body);
            sts.Add(Stm.Comment("</foreach>"));
        }
示例#7
0
        public void ThreadWriteStmClassObject()
        {
            var s = Stm.CreateObject(new MyTestClass {
                MyProp = 1
            });

            var are = new AutoResetEvent(false);

            new Thread(() =>
            {
                using (Stm.BeginTransaction())
                {
                    s.Write(new MyTestClass {
                        MyProp = 2
                    });
                }

                are.Set();
            }).Start();

            are.WaitOne();

            var v = s.Value;

            Assert.IsTrue(v.MyProp == 2);
        }
示例#8
0
 private void TranslateStm(Stm stm)
 {
     if (stm is CJUMP)
     {
         TranslateStm(stm as CJUMP);
     }
     else if (stm is EXP)
     {
         TranslateStm(stm as EXP);
     }
     else if (stm is JUMP)
     {
         TranslateStm(stm as JUMP);
     }
     else if (stm is LABEL)
     {
         TranslateStm(stm as LABEL);
     }
     else if (stm is MOVE)
     {
         TranslateStm(stm as MOVE);
     }
     else
     {
         throw new FatalError("Error in IR to TA: Stm");
     }
 }
示例#9
0
        public void FiveThreadTest()
        {
            const int nbrThreads = 5;

            var threadPool = new List <Thread>();

            for (var i = 0; i < nbrThreads; i++)
            {
                threadPool.Add(new Thread(() => DoAction()));
            }


            for (var i = 0; i < nbrStms; i++)
            {
                StmInts.Add(Stm.CreateObject(i));
            }

            var s = new Stopwatch();

            s.Start();

            foreach (var t in threadPool)
            {
                t.Start();
            }

            foreach (var t in threadPool)
            {
                t.Join();
            }

            s.Stop();

            Debug.WriteLine("Time {0}millisecondds", s.ElapsedMilliseconds);
        }
示例#10
0
        public void CreateStmClassObject()
        {
            var s = Stm.CreateObject(new MyTestClass {
                MyProp = 1
            });

            Assert.IsTrue(s.Value.MyProp == 1);
        }
示例#11
0
        private void ThreadAcquire(ConcurrentBag <Tuple <AcquireState, StmObject <int> > > acquireStates)
        {
            var t = Stm.BeginTransaction();

            s1.Read();

            acquireStates.Add(Tuple.Create(t.TransactionLog.Transactions.First().Value.Acquire(), s1));
        }
示例#12
0
        public void ReadStmIntObject()
        {
            var s = Stm.CreateObject(1);

            var t = Stm.BeginTransaction();

            var r = s.Read();

            Assert.IsTrue(r == 1);
        }
示例#13
0
        public void ReadStmClassObject()
        {
            var s = Stm.CreateObject(new MyTestClass {
                MyProp = 1
            });

            var t = Stm.BeginTransaction();

            var r = s.Read();

            Assert.IsTrue(r.MyProp == 1);
        }
示例#14
0
        public void WriteStmIntObjectCommit()
        {
            var s = Stm.CreateObject(1);

            var t = Stm.BeginTransaction();

            s.Write(2);

            var r = s.Read();

            t.Commit();

            Assert.IsTrue(r == 2);
        }
示例#15
0
 private void TranslateStm(Stm stm)
 {
     if (stm is CJUMP)
         TranslateStm(stm as CJUMP);
     else if (stm is EXP)
         TranslateStm(stm as EXP);
     else if (stm is JUMP)
         TranslateStm(stm as JUMP);
     else if (stm is LABEL)
         TranslateStm(stm as LABEL);
     else if (stm is MOVE)
         TranslateStm(stm as MOVE);
     else
         throw new FatalError("Error in IR to TA: Stm");
 }
示例#16
0
            public void ProcessEntryExit(Level level, Exp body, bool returnValue)
            {
                Stm stm = null;

                if (returnValue)
                {
                    stm = new MOVE(new TEMP(level.Frame.RV()), body.UnEx());
                }
                else
                {
                    stm = body.UnNx();
                }
                stm = level.Frame.ProcessEntryExit1(stm);
                AddFrag(new ProcFrag(stm, level.Frame));
            }
示例#17
0
            public Exp TranslateMultiArrayExp(Level home, Exp init, Exp size)
            {
                Expr alloc = home.Frame.ExternalCall("_malloc",
                                                     new Tree.ExpList(
                                                         new BINOP(BINOP.Op.Times, size.UnEx(), new CONST(Frame.WordSize())),
                                                         null));

                Temp.Temp addr    = new Temp.Temp();
                Access    var     = home.AllocLocal(false);
                Stm       initial = (new ForExp(home, var, new Ex(new CONST(0)),
                                                new Ex(new BINOP(BINOP.Op.Minus, size.UnEx(), new CONST(1))),
                                                new Nx(new MOVE(new MEM(new BINOP(BINOP.Op.Plus, new TEMP(addr), new BINOP(BINOP.Op.Times, var.Acc.Exp(null), new CONST(Frame.WordSize())))),
                                                                init.UnEx())),
                                                new Label())).UnNx();

                return(new Ex(new ESEQ(new SEQ(new MOVE(new TEMP(addr), alloc), initial), new TEMP(addr))));
            }
示例#18
0
        private void ThreadAcquireAndCommit(int newValue, ConcurrentBag <Tuple <AcquireState, StmObject <int> > > acquireStates)
        {
            var t = Stm.BeginTransaction();

            s1.Write(newValue);

            var tle           = t.TransactionLog.Transactions.First().Value;
            var acquireStatus = tle.Acquire();

            if (acquireStatus == AcquireState.Acquired)
            {
                tle.Commit();
                _commitedValue = s1.Value;
            }

            acquireStates.Add(Tuple.Create(acquireStatus, s1));
        }
        public void TestCorrectSTMWork()
        {
            Stm.Init();
            File.WriteAllText(logFileName, string.Empty);
            var variable_1 = new StmMemory <int>();
            var variable_2 = new StmMemory <int>();

            File.WriteAllText("Log.txt", string.Empty);
            List <Action> actions = new List <Action>()
            {
                new Action(() => {
                    Stm.Do(new TransactionalAction((IStmTransaction transaction) => {
                        variable_1.Set(2, transaction);
                        variable_2.Set(3, transaction);
                    }));
                }),
                new Action(() => {
                    Stm.Do(new TransactionalAction((IStmTransaction transaction) => {
                        variable_1.Set(3, transaction);
                        variable_2.Set(4, transaction);
                    }));
                }),
                new Action(() => {
                    Stm.Do(new TransactionalAction((IStmTransaction transaction) => {
                        variable_1.Get(transaction);
                        variable_2.Get(transaction);
                    }));
                }),
            };
            List <Task> tasks = new List <Task>();

            foreach (Action action in actions)
            {
                tasks.Add(Task.Run(action));
            }
            foreach (Task task in tasks)
            {
                task.Wait();
            }
            List <KeyValuePair <int, TRANSACTION_ACTION> > actionsSequence = GetTransactionActionsSequence();

            TestActionCount(actionsSequence, TRANSACTION_ACTION.COMMIT, 3);
            TestActionCount(actionsSequence, TRANSACTION_ACTION.CONFLICT, 2 + 1, true);
            TestTransactionsActionsSequence(actionsSequence);
        }
示例#20
0
        public void WriteStmClassObjectCommit()
        {
            var s = Stm.CreateObject(new MyTestClass {
                MyProp = 1
            });

            var t = Stm.BeginTransaction();

            s.Write(new MyTestClass {
                MyProp = 2
            });

            var r = s.Read();

            t.Commit();

            Assert.IsTrue(r.MyProp == 2);
        }
示例#21
0
        public override void Close()
        {
            if (_currentStream != null)
            {
                _currentStream.Close();
                _currentStream = null;
            }

            if (_watcher != null)
            {
                _watcher.Dispose();
                _watcher = null;
            }

            _current = null;
            _pos     = 0;
            _length  = 0;
            base.Close();
        }
示例#22
0
        public void ThreadWriteStmIntObject()
        {
            var s = Stm.CreateObject(1);

            var are = new AutoResetEvent(false);

            new Thread(() =>
            {
                var t1 = Stm.BeginTransaction();
                s.Write(2);

                t1.Commit();

                are.Set();
            }).Start();

            are.WaitOne();

            var v = s.Value;

            Assert.IsTrue(v == 2);
        }
        public ClassDeclaration AddClass(NamespaceDeclaration ns)
        {
            ClassDeclaration col = ns.AddClass(this.DictionaryName);

            // set base class as CollectionBase
            col.Parent = new TypeTypeDeclaration(typeof(DictionaryBase));

            // default constructor
            col.AddConstructor();

            // add indexer
            if (this.ItemGet || this.ItemSet)
            {
                IndexerDeclaration index = col.AddIndexer(
                    this.ValueType
                    );
                ParameterDeclaration pindex = index.Signature.Parameters.Add(KeyType, "key", false);

                // get body
                if (this.ItemGet)
                {
                    index.Get.Return(
                        (Expr.This.Prop("Dictionary").Item(Expr.Arg(pindex)).Cast(this.ValueType)
                        )
                        );
                }
                // set body
                if (this.ItemSet)
                {
                    index.Set.Add(
                        Stm.Assign(
                            Expr.This.Prop("Dictionary").Item(Expr.Arg(pindex)),
                            Expr.Value
                            )
                        );
                }
            }

            // add method
            if (this.Add)
            {
                MethodDeclaration    add    = col.AddMethod("Add");
                ParameterDeclaration pKey   = add.Signature.Parameters.Add(this.KeyType, "key", true);
                ParameterDeclaration pValue = add.Signature.Parameters.Add(this.ValueType, "value", true);
                add.Body.Add(
                    Expr.This.Prop("Dictionary").Method("Add").Invoke(pKey, pValue)
                    );
            }

            // contains method
            if (this.Contains)
            {
                MethodDeclaration contains = col.AddMethod("Contains");
                contains.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool));
                ParameterDeclaration pKey = contains.Signature.Parameters.Add(this.KeyType, "key", true);
                contains.Body.Return(
                    Expr.This.Prop("Dictionary").Method("Contains").Invoke(pKey)
                    );
            }

            // remove method
            if (this.Remove)
            {
                MethodDeclaration    remove = col.AddMethod("Remove");
                ParameterDeclaration pKey   = remove.Signature.Parameters.Add(this.KeyType, "key", true);

                remove.Body.Add(
                    Expr.This.Prop("Dictionary").Method("Remove").Invoke(pKey)
                    );
            }

            return(col);
        }
 public void Return(Expression expression)
 {
     this.Add(Stm.Return(expression));
 }
示例#25
0
        protected byte[] DownloadCore()
        {
            WebRequest  Web;
            WebResponse Rsp;

            System.IO.Stream Stm;

            Web = WebRequest.Create(_url);

            HttpRequest Request = HttpContext.Current.Request;

            string cookies = Request.Headers["Cookie"];

            Web.Headers.Add(HttpRequestHeader.Cookie, cookies);
            ((HttpWebRequest)Web).UserAgent = @"Mozilla/4.0 (compatible; Shotgun Webdownloader 1.0; Windows NT 5.1; )";

            if (_postdata != null)
            {//以post方式提交
                Web.Method = "POST";
                if (_Encoder == null)
                {
                    _Encoder = System.Text.ASCIIEncoding.UTF8;
                }
                ((HttpWebRequest)Web).ServicePoint.Expect100Continue = false;
                //Web.Headers[HttpRequestHeader.ContentLength] = _Encoder.EncodingName;
                Web.Headers[HttpRequestHeader.ContentEncoding] = _Encoder.WebName;
                ((HttpWebRequest)Web).ContentType = @"application/x-www-form-urlencoded";
                StreamWriter pdStm = new StreamWriter(Web.GetRequestStream(), _Encoder);
                pdStm.Write(_postdata);
                pdStm.Close();
                pdStm.Dispose();
            }

            //Web.Timeout = _timeOut;

            try
            {
                Rsp = Web.GetResponse();
            }
            catch (Exception ex)
            {
                if (Request.IsLocal)
                {
                    throw ex;
                }
                return(null);
            }

            int MaxLength, RecvicedLength, r;

            MaxLength      = (int)Rsp.ContentLength;
            RecvicedLength = 0;
            byte[] bin = new byte[MaxLength];

            Stm = Rsp.GetResponseStream();

            do
            {
                r = Stm.Read(bin, RecvicedLength, MaxLength - RecvicedLength);
                RecvicedLength += r;
            }while (RecvicedLength < MaxLength);
            Stm.Close();
            Stm.Dispose();
            Rsp.Close();
            return(bin);
        }
示例#26
0
 public void PrintStm(Stm s)
 {
     PrintStm(s, 0); Say("\n");
 }
示例#27
0
文件: Tree.cs 项目: Nxun/Naive-Tiger
 public StmList(Stm head, StmList tail)
 {
     Head = head;
     Tail = tail;
 }
示例#28
0
文件: Tree.cs 项目: Nxun/Naive-Tiger
 public ESEQ(Stm stm, Expr exp)
 {
     Stm = stm;
     Exp = exp;
 }
示例#29
0
 public abstract Stm ProcessEntryExit1(Stm body);
示例#30
0
        private void specStm(Stm e, Env <Spec> env)
        {
            C.Nn(e, env);

            switch (e)
            {
            case Declr d:
                if (d.Exp == null)
                {
                    env.Declare(d, NotSetSpec.Instance);
                }
                else
                {
                    env.Declare(d, specExp(d.Exp, env, AnySpec.Instance));
                    if (d.Exp is Ident fromIdent)
                    {
                        d.AssignedFrom.Add(fromIdent);
                    }
                    d.Ident.Spec = d.Exp.Spec;
                }

                break;

            case Assign a:
                switch (a.To)
                {
                case Ident ident:
                {
                    var orig  = env.Get(ident, true).Value;
                    var slot3 = orig == NotSetSpec.Instance ? AnySpec.Instance : orig;
                    var s     = specExp(a.Exp, env, slot3);
                    if (orig == NotSetSpec.Instance)
                    {
                        env.Set(ident, s);
                    }
                    if (a.Exp is Ident fromIdent)
                    {
                        a.AssignedFrom.Add(fromIdent);
                    }

                    break;
                }

                case MemberAccess ma:
                {
                    var minObjEnv = env.Create();
                    var declr     = new Let(
                        new Ident(ma.Ident.Name, ma.Ident.TokenType)
                        .CopyInfoFrom(ma.Ident, true), Void.Instance);
                    minObjEnv.Declare(declr, AnySpec.Instance);
                    var minObj = new ObjSpec(minObjEnv);
                    var maExpS = specExp(ma.Exp, env, minObj);
                    if (maExpS is ObjSpec objS)
                    {
                        var orig  = objS.Env.Get(ma.Ident, true).Value;
                        var slot3 = orig == NotSetSpec.Instance ? AnySpec.Instance : orig;
                        var s     = specExp(a.Exp, env, slot3);
                        if (orig == AnySpec.Instance)
                        {
                            objS.Env.Set(ma.Ident, s);
                            a.AssignedFrom.Add(ma.Ident);
                        }
                    }

                    break;
                }

                default:
                    throw new NotSupportedException();
                }

                break;

            case Return r:
                var slot2 = returns.Peek();
                var retS  = specExp(r.Exp, env, slot2 == NotSetSpec.Instance ? AnySpec.Instance : slot2);
                returns.UpdateTop(retS);
                break;

            case Loop l:
                specSequence(l.Body, env);
                break;

            case Break _:
                break;

            case Continue _:
                break;

            case Toss ts:
                var _ = specExp(ts.Exception, env, AnySpec.Instance);
                // TODO requires exp to be of some type?
                break;

            case Attempt att:
                specSequence(att.Body, env);
                if (att.Grab != null)
                {
                    var grabEnv = env.Create();
                    var exDeclr = new Let(new Ident("exception", TokenType.Ident));
                    grabEnv.Declare(exDeclr, AnySpec.Instance);
                    specSequence(att.Grab, grabEnv);
                }

                if (att.AtLast != null)
                {
                    specSequence(att.AtLast, env);
                }
                break;

            case Import imp:
                isImportContext = true;
                var objSpecWithNoMembers = new ObjSpec(env.Create());
                var modImpEl             = specExp(imp.QualifiedIdent, env, objSpecWithNoMembers);
                isImportContext = false;
                if (modImpEl is ObjSpec modImp)
                {
                    env.AddImport(imp.QualifiedIdent, modImp.Env, (Declr)modImp.Parent);
                }
                break;

            case Sequence seq:
                specSequence(seq, env);
                break;

            default:
                throw new NotSupportedException();
            }
        }
示例#31
0
 void PrintStm(Stm s, int d)
 {
     if (s is SEQ) PrintStm((SEQ)s, d);
     else if (s is LABEL) PrintStm((LABEL)s, d);
     else if (s is JUMP) PrintStm((JUMP)s, d);
     else if (s is CJUMP) PrintStm((CJUMP)s, d);
     else if (s is MOVE) PrintStm((MOVE)s, d);
     else if (s is EXP) PrintStm((EXP)s, d);
     else throw new FatalError("Print.PrintStm");
 }
 public virtual void AddAssign(Expression left, Expression right)
 {
     this.Add(Stm.Assign(left, right));
 }
示例#33
0
        public override void Generate()
        {
            // generate data
            this.Data.NamespaceDeclaration = this.NamespaceDeclaration;
            this.Data.Generate();

            // generate the rest
            this.NamespaceDeclaration.Imports.Add("System.Data");

            // create class
            ClassDeclaration c = this.NamespaceDeclaration.AddClass(this.DataReaderName);

            // IDisposable
            c.Interfaces.Add(typeof(IDisposable));

            // add datareader field
            FieldDeclaration dr = c.AddField(typeof(IDataReader), "dr");

            // add data field
            FieldDeclaration data = c.AddField(
                this.Data.DataName
                , "data");

            data.InitExpression =
                Expr.New(data.Type);
            PropertyDeclaration datap = c.AddProperty(data, true, false, false);

            // foreach field values, add get property
            foreach (DictionaryEntry de in this.Data.Properties)
            {
                DictionaryEntry     dde = (DictionaryEntry)de.Key;
                PropertyDeclaration pd  = (PropertyDeclaration)de.Value;

                PropertyDeclaration pcd = c.AddProperty(pd.Type, pd.Name);
                pcd.Get.Return(
                    Expr.This.Field(data).Prop(pd)
                    );
            }


            // add constructor
            ConstructorDeclaration cs  = c.AddConstructor();
            ParameterDeclaration   drp = cs.Signature.Parameters.Add(dr.Type, "dr", false);

            cs.Body.Add(Stm.ThrowIfNull(drp));
            cs.Body.Add(
                Stm.Assign(
                    Expr.This.Field(dr),
                    Expr.Arg(drp)
                    )
                );

            // add close method
            MethodDeclaration close = c.AddMethod("Close");

            // if dr ==null return;
            close.Body.Add(
                Stm.IfNull(Expr.This.Field(dr), Stm.Return())
                );
            // dr.Close();
            close.Body.Add(
                Expr.This.Field(dr).Method("Close").Invoke()
                );
            // dr = null;
            close.Body.AddAssign(Expr.This.Field(dr), Expr.Null);
            // data = null
            close.Body.AddAssign(Expr.This.Field(data), Expr.Null);

            // add read method
            MethodDeclaration read = c.AddMethod("Read");

            read.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool));

            // if (!dr.Read()){close and return)
            ConditionStatement ifnotread = Stm.IfIdentity(
                Expr.This.Field(dr).Method("Read").Invoke(),
                Expr.False,
                Stm.ToStm(Expr.This.Method(close).Invoke()),
                Stm.Return(Expr.False)
                );

            read.Body.Add(ifnotread);


            // foreach field values
            foreach (DictionaryEntry de in this.Data.Properties)
            {
                DictionaryEntry     dde = (DictionaryEntry)de.Key;
                PropertyDeclaration pd  = (PropertyDeclaration)de.Value;
                read.Body.AddAssign(
                    Expr.This.Field(data).Prop(pd),
                    (
                        Expr.This.Field(dr).Item(Expr.Prim(dde.Key.ToString()))
                    ).Cast(dde.Value.ToString())
                    );
            }
            // return true
            read.Body.Return(Expr.True);

            // add dispose method
            MethodDeclaration dispose = c.AddMethod("Dispose");

            dispose.ImplementationTypes.Add(typeof(IDisposable));

            // Close();
            dispose.Body.Add(
                Expr.This.Method(close).Invoke()
                );

            if (this.Enumerator)
            {
                AddEnumerator(c, data, close);
            }
        }
示例#34
0
        private void AddArrayField(ClassDeclaration c, FieldInfo f)
        {
            // create a collection
            ClassDeclaration col = c.AddClass(conformer.ToSingular(f.Name) + "Collection");

            col.Parent = new TypeTypeDeclaration(typeof(System.Collections.CollectionBase));

            // add serializable attribute
            col.CustomAttributes.Add(typeof(SerializableAttribute));

            // default constructor
            col.AddConstructor();
            // default indexer
            IndexerDeclaration index = col.AddIndexer(
                typeof(Object)
                );
            ParameterDeclaration pindex = index.Signature.Parameters.Add(typeof(int), "index", false);

            // getter
            index.Get.Return(
                Expr.This.Prop("List").Item(Expr.Arg(pindex))
                );
            index.Set.AddAssign(
                Expr.This.Prop("List").Item(Expr.Arg(pindex)),
                Expr.Value
                );

            // add object method
            MethodDeclaration    addObject  = col.AddMethod("Add");
            ParameterDeclaration paraObject = addObject.Signature.Parameters.Add(new TypeTypeDeclaration(typeof(Object)), "o", true);

            addObject.Body.Add(
                Expr.This.Prop("List").Method("Add").Invoke(paraObject)
                );

            // if typed array add methods for type
            if (f.FieldType.GetElementType() != typeof(Object))
            {
                AddCollectionMethods(
                    col,
                    MapType(f.FieldType.GetElementType()),
                    this.conformer.ToCapitalized(f.FieldType.GetElementType().Name),
                    "o"
                    );
            }

            foreach (XmlElementAttribute ea in f.GetCustomAttributes(typeof(XmlElementAttribute), true))
            {
                string name  = this.conformer.ToCapitalized(ea.ElementName);
                string pname = this.conformer.ToCamel(name);

                ITypeDeclaration mappedType = null;
                if (ea.Type != null)
                {
                    mappedType = MapType(ea.Type);
                }

                if (mappedType == null || mappedType == f.FieldType.GetElementType())
                {
                    continue;
                }

                AddCollectionMethods(col, mappedType, name, pname);
            }

            // add field
            FieldDeclaration fd = c.AddField(col, f.Name);

            fd.InitExpression = Expr.New(col);
            PropertyDeclaration p = c.AddProperty(fd, f.Name, true, true, false);

            // setting attributes
            // attach xml text
            if (TypeHelper.HasCustomAttribute(f, typeof(XmlTextAttribute)))
            {
                AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlTextAttribute));

                attr.Arguments.Add("Type", Expr.TypeOf(typeof(string)));

                // adding to string to collection
                MethodDeclaration tostring = col.AddMethod("ToString");
                tostring.Signature.ReturnType = new TypeTypeDeclaration(typeof(String));
                tostring.Attributes           = MemberAttributes.Public | MemberAttributes.Override;

                VariableDeclarationStatement sw = Stm.Var(typeof(StringWriter), "sw");
                sw.InitExpression = Expr.New(typeof(StringWriter));
                tostring.Body.Add(sw);
                ForEachStatement fe = Stm.ForEach(
                    typeof(string), "s", Expr.This.Prop("List"), false);

                fe.Body.Add(
                    Expr.Var(sw).Method("Write").Invoke(fe.Local)
                    );

                tostring.Body.Add(fe);
                tostring.Body.Return(Expr.Var(sw).Method("ToString").Invoke());
            }
            else if (TypeHelper.HasCustomAttribute(f, typeof(XmlArrayItemAttribute)))
            {
                // add xml array attribute
                AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlArrayAttribute));
                attr.Arguments.Add("ElementName", Expr.Prim(f.Name));

                // add array item attribute
                XmlArrayItemAttribute arrayItem =
                    (XmlArrayItemAttribute)TypeHelper.GetFirstCustomAttribute(f, typeof(XmlArrayItemAttribute));

                attr = p.CustomAttributes.Add(typeof(XmlArrayItemAttribute));
                attr.Arguments.Add("ElementName", Expr.Prim(arrayItem.ElementName));
                //MMI:attr.Arguments.Add("Type",Expr.Prim(MapType(f.FieldType.GetElementType()).Name));
                attr.Arguments.Add("Type", Expr.TypeOf(MapType(f.FieldType.GetElementType())));

                if (arrayItem.Type != null)
                {
                    attr.Arguments.Add("DataType", Expr.Prim(arrayItem.DataType));
                }
                attr.Arguments.Add("IsNullable", Expr.Prim(arrayItem.IsNullable));
                if (this.Config.KeepNamespaces)
                {
                    attr.Arguments.Add("Namespace", Expr.Prim(arrayItem.Namespace));
                }
            }
            else
            {
                AttachXmlElementAttributes(p, f);
            }
        }
        public ClassDeclaration AddClass(NamespaceDeclaration ns)
        {
            ClassDeclaration col = ns.AddClass(this.CollectionName);

            // set base class as CollectionBase
            col.Parent = new TypeTypeDeclaration(typeof(CollectionBase));

            // default constructor
            col.AddConstructor();

            // add indexer
            if (this.ItemGet || this.ItemSet)
            {
                IndexerDeclaration index = col.AddIndexer(
                    this.Type
                    );
                ParameterDeclaration pindex = index.Signature.Parameters.Add(typeof(int), "index", false);

                // get body
                if (this.ItemGet)
                {
                    index.Get.Return(
                        (Expr.This.Prop("List").Item(Expr.Arg(pindex)).Cast(this.Type)
                        )
                        );
                }
                // set body
                if (this.ItemSet)
                {
                    index.Set.Add(
                        Stm.Assign(
                            Expr.This.Prop("List").Item(Expr.Arg(pindex)),
                            Expr.Value
                            )
                        );
                }
            }

            string pname = ns.Conformer.ToCamel(this.Type.Name);

            // add method
            if (this.Add)
            {
                MethodDeclaration    add  = col.AddMethod("Add");
                ParameterDeclaration para = add.Signature.Parameters.Add(this.Type, pname, true);
                add.Body.Add(
                    Expr.This.Prop("List").Method("Add").Invoke(para)
                    );
            }

            if (this.AddRange)
            {
                MethodDeclaration    add  = col.AddMethod("AddRange");
                ParameterDeclaration para = add.Signature.Parameters.Add(col, pname, true);

                ForEachStatement fe = Stm.ForEach(
                    this.Type,
                    "item",
                    Expr.Arg(para),
                    false
                    );
                fe.Body.Add(
                    Expr.This.Prop("List").Method("Add").Invoke(fe.Local)
                    );

                add.Body.Add(fe);
            }

            // contains method
            if (this.Contains)
            {
                MethodDeclaration contains = col.AddMethod("Contains");
                contains.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool));
                ParameterDeclaration para = contains.Signature.Parameters.Add(this.Type, pname, true);
                contains.Body.Return(
                    Expr.This.Prop("List").Method("Contains").Invoke(para)
                    );
            }

            // remove method
            if (this.Remove)
            {
                MethodDeclaration    remove = col.AddMethod("Remove");
                ParameterDeclaration para   = remove.Signature.Parameters.Add(this.Type, pname, true);

                remove.Doc.Summary.AddText("Removes the first occurrence of a specific ParameterDeclaration from this ParameterDeclarationCollection.");

                remove.Body.Add(
                    Expr.This.Prop("List").Method("Remove").Invoke(para)
                    );
            }

            // insert
            if (this.Insert)
            {
                MethodDeclaration    insert = col.AddMethod("Insert");
                ParameterDeclaration index  = insert.Signature.Parameters.Add(typeof(int), "index", true);
                ParameterDeclaration para   = insert.Signature.Parameters.Add(this.Type, pname, true);
                insert.Body.Add(
                    Expr.This.Prop("List").Method("Insert").Invoke(index, para)
                    );
            }

            // indexof
            if (this.IndexOf)
            {
                MethodDeclaration    indexof = col.AddMethod("IndexOf");
                ParameterDeclaration para    = indexof.Signature.Parameters.Add(this.Type, pname, true);
                indexof.Signature.ReturnType = new TypeTypeDeclaration(typeof(int));
                indexof.Body.Return(
                    Expr.This.Prop("List").Method("IndexOf").Invoke(para)
                    );
            }

            if (this.Enumerator)
            {
                // create subclass
                ClassDeclaration en = col.AddClass("Enumerator");
                // add wrapped field
                FieldDeclaration wrapped = en.AddField(
                    typeof(IEnumerator), "wrapped"
                    );
                // add IEnumerator
                en.Interfaces.Add(typeof(IEnumerator));

                // add constructor
                ConstructorDeclaration cs         = en.AddConstructor();
                ParameterDeclaration   collection = cs.Signature.Parameters.Add(col, "collection", true);
                cs.Body.Add(
                    Stm.Assign(
                        Expr.This.Field(wrapped),
                        Expr.Arg(collection).Cast(typeof(CollectionBase)).Method("GetEnumerator").Invoke()
                        )
                    );

                // add current
                PropertyDeclaration current = en.AddProperty(this.Type, "Current");
                current.Get.Return(
                    (Expr.This.Field(wrapped).Prop("Current")).Cast(this.Type)
                    );

                // add explicit interface implementation
                PropertyDeclaration currentEn = en.AddProperty(typeof(Object), "Current");
                currentEn.Get.Return(Expr.This.Prop(current));
                currentEn.PrivateImplementationType = wrapped.Type;

                // add reset
                MethodDeclaration reset = en.AddMethod("Reset");
                reset.ImplementationTypes.Add(wrapped.Type);
                reset.Body.Add(Expr.This.Field(wrapped).Method("Reset").Invoke());

                // add movenext
                MethodDeclaration movenext = en.AddMethod("MoveNext");
                movenext.ImplementationTypes.Add(wrapped.Type);
                movenext.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool));
                movenext.Body.Return(Expr.This.Field(wrapped).Method("MoveNext").Invoke());

                // add get enuemrator
                MethodDeclaration geten = col.AddMethod("GetEnumerator");
                geten.Attributes |= MemberAttributes.New;
                geten.ImplementationTypes.Add(new TypeTypeDeclaration(typeof(IEnumerable)));
                geten.Signature.ReturnType = en;
                geten.Body.Return(Expr.New(en, Expr.This));
            }

            return(col);
        }
示例#36
0
文件: Tree.cs 项目: Nxun/Naive-Tiger
 public SEQ(Stm left, Stm right)
 {
     Left = left;
     Right = right;
 }
示例#37
0
 public Nx(Stm stm)
 {
     Stm = stm;
 }
示例#38
0
文件: Frame.cs 项目: Nxun/Naive-Tiger
 public abstract Stm ProcessEntryExit1(Stm body);
示例#39
0
 public ProcFrag(Stm b, Frame.Frame f)
 {
     Body = b;
     Frame = f;
 }