Example #1
0
        internal static void Issue052_DuplicatorPostCustomizable(Fake <CopyHint> hint, Data item)
        {
            IDuplicator duplicator = new Duplicator(Tools.Asserter, false);

            hint.Setup(
                d => d.TryCopy(item, Arg.Any <DuplicatorChainer>()),
                Behavior.Returns((true, (object)item), Times.Once));

            duplicator.AddHint(hint.Dummy);
            duplicator.Copy(item).Assert().ReferenceEqual(item);
            hint.VerifyAll();
        }
        internal static void Copy_ValidHintWorks(object data, Fake <CopyHint> hint)
        {
            hint.Setup(
                m => m.TryCopy(data, Arg.Any <DuplicatorChainer>()),
                Behavior.Returns((true, data), Times.Once));

            object result = new Duplicator(Tools.Asserter, false, hint.Dummy).Copy(data);

            Tools.Asserter.CheckAll(
                () => Tools.Asserter.Is(data, result),
                () => hint.VerifyAll(Times.Once));
        }
Example #3
0
        public void SaveEdit(string action = "")
        {
            using (var scope = new TransactionScope())
            {
                if (Id == Guid.Empty)
                {
                    Id                = Guid.NewGuid();
                    CreateTime        = DateTime.Now;
                    LastUpdateTime    = DateTime.Now;
                    CreateUserAccount = ClientCookie.UserCode;

                    IsHistory = false;

                    Add(this);
                }
                else
                {
                    LastUpdateTime = DateTime.Now;
                    Update(this);
                }
                if (ReinBasicInfo != null)
                {
                    var ReinBasicInfo_New = Duplicator.AutoCopy(ReinBasicInfo);

                    ReinBasicInfo_New.ConsInfoID = Id;
                    ReinBasicInfo_New.Add();
                }

                if (ReinCost != null)
                {
                    var ReinCost_New = Duplicator.AutoCopy(ReinCost);
                    ReinCost_New.Id         = Guid.NewGuid();
                    ReinCost_New.ConsInfoID = Id;
                    ReinCost_New.Add();
                }

                if (WriteOff != null)
                {
                    var WriteOff_New = Duplicator.AutoCopy(WriteOff);
                    WriteOff_New.Id         = Guid.NewGuid();
                    WriteOff_New.ConsInfoID = Id;
                    WriteOff_New.Add();
                }
                SaveApproveUsers(action);
                if (string.Compare(action, "edit", true) != 0)
                {
                    SaveComments(action);
                }
                scope.Complete();
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            // Parameters Check
            if (args == null || args.Length == 0)
            {
                // Error
                Console.WriteLine("No arguments received. Type pass '-h' to receive a list of parameters");
                System.Environment.Exit(-101);
            }

            // Should print help ?
            if (args.Where(t => t == "-h").FirstOrDefault() != null)
            {
                // Printing Help - Parameters
                PrintHelp();
                return;
            }

            // Reading App Config
            LoadConfiguration();

            // Parsing Arguments
            ParseArguments(args);

            Console.WriteLine("Reaching Database");

            // Building Connection Strings
            String sourceConnString = MongoDbContext.BuildConnectionString(_sourceUsername, _sourcePassword, _sourceServer, _authDatabaseName);

            // Reaching Database
            MongoDatabase sourceDatabase = MongoDbContext.GetServer(sourceConnString).GetDatabase(_sourceDatabaseName);

            // Picking which method to use
            switch (_duplicateMode)
            {
            case DuplicateMode.DuplicateCollections:
                Console.WriteLine("Duplicating collection from List");
                Duplicator.CollectionsDuplicate(sourceDatabase, _collections, _insertBatchSize, _copyIndexes, _duplicationSuffix);
                break;

            case DuplicateMode.DuplicateCollectionsWithMask:
                Console.WriteLine("Duplicating Collections that matches : " + _collections.Value.First());
                Duplicator.CollectionsDuplicate(sourceDatabase, _collections.Value.First(), _insertBatchSize, _copyIndexes, _duplicationSuffix);
                break;
            }

            Console.WriteLine("Duplication Finished");
            Console.ReadLine();
        }
Example #5
0
        private Procedure CreateNewProcedure(Implementation impl, List <IdentifierExpr> modifies)
        {
            var newModifies = new List <IdentifierExpr>();

            foreach (var mod in modifies)
            {
                var newVar = new Duplicator().Visit(mod.Decl.Clone()) as Variable;
                newModifies.Add(new IdentifierExpr(Token.NoToken, newVar));
            }

            impl.Proc = new Procedure(Token.NoToken, impl.Name, new List <TypeVariable>(),
                                      impl.InParams, impl.OutParams, new List <Requires>(), newModifies,
                                      new List <Ensures>(), impl.Attributes);

            return(impl.Proc);
        }
Example #6
0
 public Expression GetExpressionTemplate(string name)
 {
     TypeNode exprClass = ((Namespace)cuExprs.Nodes[0]).Types[0];
     for (int i = 0; i < exprClass.Members.Count; i++)
     {
         Field f = exprClass.Members[i] as Field;
         if (f != null && f.Name.Name == name)
         {
             Duplicator duplicator = new Duplicator(module, null);
             duplicator.SkipBodies = false;
             return duplicator.VisitExpression(f.Initializer);
         }
     }
     throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture,
         "Expression template '{0}' not found", name));
 }
Example #7
0
        public Method GetMethodTemplate(string name)
        {
            for (int i = 0, n = ((Namespace)cuStatements.Nodes[0]).Types[0].Members.Count; i < n; i++)
            {
                Method m = ((Namespace)cuStatements.Nodes[0]).Types[0].Members[i] as Method;

                if (m != null && m.Name.Name == name)
                {
                    Duplicator duplicator = new Duplicator(module, null);
                    duplicator.SkipBodies = false;
                    return (Method)duplicator.Visit(m);
                }
            }
            throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture,
                "Method template '{0}' not found", name));
        }
Example #8
0
 public Constraint(Constraint cons, bool copy)
 {
     if (!copy)
     {
         Conjuncts = new List <Expr>(cons.Conjuncts);
     }
     else
     {
         var duper = new Duplicator();
         Conjuncts = new List <Expr>(cons.Conjuncts.Count);
         foreach (var e in cons.Conjuncts)
         {
             Conjuncts.Add(duper.VisitExpr(e));
         }
     }
 }
Example #9
0
 public override Expr VisitIdentifierExpr(IdentifierExpr expr)
 {
     if (!defs.ContainsKey(expr.Decl))
     {
         return(base.VisitIdentifierExpr(expr));
     }
     else if (defs[expr.Decl] == null)
     {
         isSubstitutable = false;
         return(null);
     }
     else
     {
         var dup = new Duplicator();
         return((Expr)dup.Visit(defs[expr.Decl]));
     }
 }
        private static TypeNodeList CreateTemplateParameters(Class closureClass, Method @from, TypeNode declaringType)
        {
            var dup = new Duplicator(declaringType.DeclaringModule, declaringType);

            var templateParameters = new TypeNodeList();

            var parentCount = declaringType.ConsolidatedTemplateParameters.CountOrDefault();

            for (int i = 0; i < from.TemplateParameters.Count; i++)
            {
                var tp = HelperMethods.NewEqualTypeParameter(
                    dup, (ITypeParameter)from.TemplateParameters[i],
                    closureClass, parentCount + i);

                templateParameters.Add(tp);
            }

            return(templateParameters);
        }
        public Implementation instrumentAssertion(Implementation impl, string label, Cmd typedCmd, AssertCmd assertion)
        {
            Implementation new_impl = new Duplicator().VisitImplementation(impl);

            this.target_label     = label;
            this.target_typedCmd  = typedCmd;
            this.target_assertion = assertion;
            if (this.target_assertion.Attributes != null)
            {
                this.target_assertion.Attributes.AddLast(new QKeyValue(Token.NoToken, "source_assert", new List <object> (), null));
            }
            else
            {
                this.target_assertion.Attributes = new QKeyValue(Token.NoToken, "source_assert", new List <object> (), null);
            }
            this.target_acquired = false;
            this.Visit(new_impl); //this step performs the instrumentation
            Utils.Assert(target_acquired, "Unable to instrument assertion: " + assertion.ToString() + " at label " + label);
            return(new_impl);
        }
Example #12
0
        public override string Edit()
        {
            var info     = RenewalInfo.Get(ProjectId);
            var analysis = Duplicator.AutoCopy(this);

            analysis.Id        = Guid.NewGuid();
            analysis.IsHistory = false;
            analysis.Add();
            this.IsHistory = true;
            this.Update();
            ProjectInfo.Reset(ProjectId, this.WorkflowCode);
            RenewalPackage package = RenewalPackage.Get(ProjectId);

            package.AnalysisId = analysis.Id;
            package.Update();
            TaskWork.Cancel(e => e.TypeCode == FlowCode.Renewal_Analysis && e.RefID == ProjectId && e.Status == TaskWorkStatus.UnFinish);
            var task = info.GenerateSubmitTask(FlowCode.Renewal_Analysis);

            return(task.Url);
        }
Example #13
0
        public override string Edit()
        {
            using (var tranScope = new TransactionScope())
            {
                var info   = RenewalInfo.Get(this.ProjectId);
                var entity = Duplicator.AutoCopy(this);
                entity.Id                = Guid.NewGuid();
                entity.IsHistory         = false;
                entity.CreateTime        = DateTime.Now;
                entity.CreateUserAccount = ClientCookie.UserCode;
                entity.Add();
                this.IsHistory = true;
                this.Update();
                ProjectInfo.Reset(ProjectId, this.WorkflowCode);
                var attachments = Attachment.GetList(this.TableName, Id.ToString(), string.Empty);
                attachments.ForEach(att =>
                {
                    att.RefTableID = entity.Id.ToString();
                    att.ID         = Guid.NewGuid();
                });
                Attachment.Add(attachments.ToArray());

                //var TypeCodes = new[] { FlowCode.Renewal_ContractInfo, FlowCode.Renewal_SiteInfo };
                //foreach (var typeCode in TypeCodes)
                //{
                //    var proj = ProjectInfo.Search(e => e.ProjectId == ProjectId && e.FlowCode == typeCode).FirstOrDefault();
                //    if (proj != null && proj.Status != ProjectStatus.Finished)
                //    {
                //        var oldTask = TaskWork.Search(t => t.RefID == ProjectId && t.Status == TaskWorkStatus.UnFinish && t.TypeCode == typeCode).FirstOrDefault();
                //        if (oldTask != null)
                //        {
                //            oldTask.Status = TaskWorkStatus.Cancel;
                //            TaskWork.Update(oldTask);
                //        }
                //    }
                //}
                var task = info.GenerateSubmitTask(this.WorkflowCode);
                tranScope.Complete();
                return(task.Url);
            }
        }
Example #14
0
        private CallCmd CreateCallCmd(Implementation impl, Implementation otherImpl, bool checkMatcher = false)
        {
            List <Expr> ins = new List <Expr>();

            for (int i = 0; i < impl.Proc.InParams.Count; i++)
            {
                if (checkMatcher && this.InParamMatcher.ContainsKey(i))
                {
                    Variable v = new Duplicator().Visit(this.InParamMatcher[i].Clone()) as Variable;
                    ins.Add(new IdentifierExpr(v.tok, v));
                }
                else
                {
                    ins.Add(new IdentifierExpr(impl.Proc.InParams[i].tok, impl.Proc.InParams[i]));
                }
            }

            var call = new CallCmd(Token.NoToken, impl.Name, ins, new List <IdentifierExpr>());

            return(call);
        }
Example #15
0
        public static Expr Resolve(Variable var, SymbolicStore store)
        {
            if (var == null || store == null)
            {
                return(null);
            }

            var resolver = new ExprResolver(store);
            var duper    = new Duplicator();
            var ret      = store.Get(new StoreLhs(var));

            if (ret == null)
            {
                Log.Out(Log.Error, "Could not find " + var.Name + " in symbolic store!");
                return(null);
            }

            ret = resolver.VisitExpr(ret);
            ret = duper.VisitExpr(ret);
            return(ret);
        }
Example #16
0
 public override string Edit()
 {
     using (TransactionScope tranScope = new TransactionScope())
     {
         Mapper.CreateMap <TempClosurePackage, TempClosurePackage>();
         var package = Mapper.Map <TempClosurePackage>(this);
         package.Id                = Guid.NewGuid();
         package.IsHistory         = false;
         package.CreateUserAccount = ClientCookie.UserCode;
         package.CreateTime        = DateTime.Now;
         Add(package);
         IsHistory = true;
         Update(this);
         ProjectInfo.Reset(ProjectId, FlowCode.TempClosure_ClosurePackage);
         ProjectInfo.Reset(ProjectId, FlowCode.TempClosure);
         var attachments = Attachment.GetList(this.TableName, Id.ToString(), "");
         var NewAtts     = new List <Attachment>();
         attachments.ForEach(att =>
         {
             var newAttach        = Duplicator.AutoCopy(att);
             newAttach.RefTableID = package.Id.ToString();
             newAttach.ID         = Guid.NewGuid();
             NewAtts.Add(newAttach);
         });
         Attachment.Add(NewAtts.ToArray());
         var assetActor = ProjectUsers.FirstOrDefault(pu => pu.ProjectId == ProjectId && pu.RoleCode == ProjectUserRoleCode.AssetActor);
         var oldTasks   = TaskWork.Search(t => t.RefID == ProjectId && t.Status == TaskWorkStatus.UnFinish).AsNoTracking().ToList();
         oldTasks.ForEach(t =>
         {
             t.Status = TaskWorkStatus.Cancel;
         });
         TaskWork.Update(oldTasks.ToArray());
         var    latestTask = TaskWork.FirstOrDefault(t => t.RefID == ProjectId && t.TypeCode == FlowCode.TempClosure_ClosurePackage);
         string url        = "/TempClosure/Main#/ClosurePackage?projectId=" + ProjectId;
         TaskWork.SendTask(ProjectId, latestTask.Title, latestTask.StoreCode, url, assetActor, FlowCode.TempClosure, FlowCode.TempClosure_ClosurePackage, "Start");
         tranScope.Complete();
         return(url);
     }
 }
        private static void ReplaceShaders(GameObject instance, string temporaryPrefabPath)
        {
            var alreadyDuplicatedMaterials = new Dictionary <Material, Material>();

            foreach (var renderer in instance.GetComponentsInChildren <SkinnedMeshRenderer>())
            {
                renderer.sharedMaterials = renderer.sharedMaterials.Select(material =>
                {
                    if (VRChatToVRMConverter.VRMSupportedShaderNames.Contains(material.shader.name))
                    {
                        return(material);
                    }

                    if (alreadyDuplicatedMaterials.ContainsKey(material))
                    {
                        return(alreadyDuplicatedMaterials[material]);
                    }

                    var newMaterial  = Object.Instantiate(material);
                    newMaterial.name = material.name;

                    var shaderName = material.shader.name.ToLower();
                    if (shaderName.Contains("unlit"))
                    {
                        newMaterial.shader = Shader.Find("UniGLTF/UniUnlit");
                    }
                    else if (shaderName.Contains("toon"))
                    {
                        newMaterial.shader = Shader.Find("VRM/MToon");
                    }
                    newMaterial.renderQueue = material.renderQueue;

                    return(alreadyDuplicatedMaterials[material]
                               = Duplicator.CreateObjectToFolder(newMaterial, temporaryPrefabPath));
                }).ToArray();
            }
        }
        /// <summary>
        /// アニメーションクリップに、指定されたマテリアルを追加します。
        /// </summary>
        /// <param name="avatar"></param>
        /// <param name="animationClip"></param>
        /// <param name="name"></param>
        /// <param name="binding"></param>
        /// <param name="secondsList"></param>
        private static void SetBlendShapeCurve(
            AnimationClip animationClip,
            GameObject avatar,
            string vrmBlendShapeName,
            IEnumerable <MaterialValueBinding> bindings,
            IEnumerable <float> secondsList
            )
        {
            var materials = avatar.transform.Find(VRChatUtility.AutoBlinkMeshPath)
                            .GetComponent <SkinnedMeshRenderer>().sharedMaterials;

            var materialIndex = materials.ToList().FindIndex(m => m.name == bindings.First().MaterialName);

            var material = Duplicator.DuplicateAssetToFolder <Material>(
                source: materials[materialIndex],
                prefabInstance: avatar,
                fileName: $"{materials[materialIndex].name}-{vrmBlendShapeName}.mat"
                );

            VRMUtility.Bake(material, bindings);

            AnimationUtility.SetObjectReferenceCurve(
                animationClip,
                new EditorCurveBinding()
            {
                path         = VRChatUtility.AutoBlinkMeshPath,
                type         = typeof(SkinnedMeshRenderer),
                propertyName = $"m_Materials.Array.data[{materialIndex}]",
            },
                secondsList
                .Select(seconds => new ObjectReferenceKeyframe()
            {
                time = seconds, value = material
            }).ToArray()
                );
        }
Example #19
0
        public override string Edit()
        {
            var info   = RenewalInfo.Get(ProjectId);
            var entity = Duplicator.AutoCopy(this);

            entity.Id        = Guid.NewGuid();
            entity.IsHistory = false;
            entity.Add();
            this.IsHistory = true;
            this.Update();
            var attachments = Attachment.GetList(this.TableName, Id.ToString(), string.Empty);

            attachments.ForEach(att =>
            {
                att.RefTableID = entity.Id.ToString();
                att.ID         = Guid.NewGuid();
            });
            Attachment.Add(attachments.ToArray());
            TaskWork.Cancel(e => e.TypeCode == this.WorkflowCode && e.RefID == ProjectId && e.Status == TaskWorkStatus.UnFinish);
            ProjectInfo.Reset(ProjectId, this.WorkflowCode);
            var task = info.GenerateSubmitTask(this.WorkflowCode);

            return(task.Url);
        }
Example #20
0
        public override string Edit()
        {
            var info   = RenewalInfo.Get(ProjectId);
            var entity = Duplicator.AutoCopy(this);

            entity.Id        = Guid.NewGuid();
            entity.IsHistory = false;
            entity.Add();
            this.IsHistory = true;
            this.Update();
            var records = RenewalLLNegotiationRecord.GetRecords(this.Id);

            records.ForEach(rec =>
            {
                rec.Id = Guid.NewGuid();
                rec.RenewalLLNegotiationId = entity.Id;
            });
            RenewalLLNegotiationRecord.Add(records.ToArray());
            TaskWork.Cancel(e => e.TypeCode == this.WorkflowCode && e.RefID == ProjectId && e.Status == TaskWorkStatus.UnFinish);
            ProjectInfo.Reset(ProjectId, this.WorkflowCode);
            var task = info.GenerateSubmitTask(this.WorkflowCode);

            return(task.Url);
        }
Example #21
0
        public override string Edit()
        {
            string url;

            using (var tranScope = new TransactionScope())
            {
                var info = RenewalInfo.Get(this.ProjectId);
                var tool = Duplicator.AutoCopy(this);
                tool.Id                = Guid.NewGuid();
                tool.IsHistory         = false;
                tool.CreateTime        = DateTime.Now;
                tool.CreateUserAccount = ClientCookie.UserCode;
                tool.Add();

                NewEntityId = tool.Id;
                IsHistory   = true;
                this.Update();
                ProjectInfo.Reset(ProjectId, this.WorkflowCode);
                var attachments = Attachment.GetList(this.TableName, Id.ToString(), string.Empty);
                attachments.ForEach(att =>
                {
                    att.RefTableID = tool.Id.ToString();
                    att.ID         = Guid.NewGuid();
                });
                Attachment.Add(attachments.ToArray());

                var FinMI    = RenewalToolFinMeasureInput.Get(this.ProjectId, this.Id);
                var newFinMI = Duplicator.AutoCopy(FinMI);
                newFinMI.Id     = Guid.NewGuid();
                newFinMI.ToolId = tool.Id;
                newFinMI.Add();

                var WfRc    = RenewalToolWriteOffAndReinCost.Get(this.ProjectId, this.Id);
                var newWfRc = Duplicator.AutoCopy(WfRc);
                newWfRc.Id     = Guid.NewGuid();
                newWfRc.ToolId = tool.Id;
                newWfRc.Add();

                var FinMO    = RenewalToolFinMeasureOutput.GetByToolId(this.Id);
                var newFinMO = Duplicator.AutoCopy(FinMO);
                newFinMO.Id     = Guid.NewGuid();
                newFinMO.ToolId = tool.Id;
                newFinMO.Add();

                var package = RenewalPackage.Get(this.ProjectId);
                package.ToolId = tool.Id;
                package.Update();

                var oldTasks = TaskWork.Search(t => t.RefID == ProjectId && t.Status == TaskWorkStatus.UnFinish && new string[] { this.WorkflowCode, FlowCode.Renewal_Analysis }.Contains(t.TypeCode)).ToList();
                oldTasks.ForEach(t =>
                {
                    t.Status = TaskWorkStatus.Cancel;
                });
                TaskWork.Update(oldTasks.ToArray());

                var anlysisProj = ProjectInfo.FirstOrDefault(e => e.FlowCode == FlowCode.Renewal_Analysis &&
                                                             e.Status == ProjectStatus.UnFinish && e.ProjectId == ProjectId);
                if (anlysisProj != null)
                {
                    var taskAnlysis = TaskWork.FirstOrDefault(e => e.TypeCode == FlowCode.Renewal_Analysis && e.RefID == ProjectId && e.Status == TaskWorkStatus.UnFinish);
                    if (taskAnlysis != null)
                    {
                        taskAnlysis.Status     = TaskWorkStatus.Finished;
                        taskAnlysis.FinishTime = DateTime.Now;
                        taskAnlysis.Update();
                    }
                }
                var task = info.GenerateSubmitTask(this.WorkflowCode);
                url = task.Url;
                tranScope.Complete();
            }

            return(url);
        }
Example #22
0
        internal Expression ContextAttributeConstructor(AttributeList attrs)
        {
            AttributeNode contextAttr = this.GetContextAttribute(attrs);

            if (contextAttr == null)
                return new Literal(null, SystemTypes.Object);

            Duplicator duplicator = new Duplicator(null, null);
            AttributeNode dupAttr = duplicator.VisitAttributeNode(contextAttr);

            Construct cons = (Construct)Templates.GetExpressionTemplate("ContextAttributeConstructor");

            Replacer.Replace(cons, "_AttributeName", dupAttr.Type.Name);

            Normalizer normalizer = new Normalizer(false);
            cons.Operands = normalizer.VisitExpressionList(dupAttr.Expressions);

            return cons;
        }
Example #23
0
        private Implementation DuplicateFunction(Thread thread, Implementation func, IdentifierExpr tid)
        {
            string suffix = "";

            if (func.Name.Equals(thread.Name))
            {
                suffix = "$" + thread.Id.Name;
            }
            else if (thread.IsMain)
            {
                suffix = "$" + thread.Name;
            }
            else
            {
                suffix = "$" + thread.Name + "$" + thread.Id.Name;
            }

            var cons = this.AC.GetConstant(func.Name);

            if (cons != null)
            {
                var consName = cons.Name + suffix;
                var newCons  = new Constant(cons.tok,
                                            new TypedIdent(cons.TypedIdent.tok, consName,
                                                           cons.TypedIdent.Type), cons.Unique);
                this.AC.TopLevelDeclarations.Add(newCons);
            }

            var newProc = new Duplicator().Visit(func.Proc.Clone()) as Procedure;
            var newImpl = new Duplicator().Visit(func.Clone()) as Implementation;

            newProc.Name = func.Proc.Name + suffix;
            newImpl.Name = func.Name + suffix;
            newImpl.Proc = newProc;

            if (func.Name.Equals(thread.Function.Name))
            {
                newImpl.Proc.Attributes = new QKeyValue(Token.NoToken,
                                                        "thread", new List <object>(), null);
                newImpl.Attributes = new QKeyValue(Token.NoToken,
                                                   "thread", new List <object>(), null);
            }
            else
            {
                newImpl.Attributes = new QKeyValue(Token.NoToken, "tag",
                                                   new List <object>()
                {
                    thread.Name
                }, func.Attributes);
                newProc.Attributes = new QKeyValue(Token.NoToken, "tag",
                                                   new List <object>()
                {
                    thread.Name
                }, func.Proc.Attributes);
            }

            if (func.Name.Equals(thread.Name))
            {
                thread.Function = newImpl;
            }

            this.AC.TopLevelDeclarations.Add(newProc);
            this.AC.TopLevelDeclarations.Add(newImpl);

            this.DuplicatedFunctions.Add(func.Name);

            return(newImpl);
        }
    static void Init()
    {
        Duplicator window = (Duplicator)EditorWindow.GetWindow(typeof(Duplicator));

        window.Show();
    }
Example #25
0
        private void AddBlockMethod(ZMethod zMethod, Class methodClass, BasicBlock block, List<Scope> nonTrivialScopes)
        {
            Method blockMethod = (Method)Templates.GetTypeTemplateByName("BlockMethod").Members[0];
            blockMethod.Name = new Identifier(block.Name);
            methodClass.Members.Add(blockMethod);
            blockMethod.DeclaringType = methodClass;

            // Generate the appropriate closing statements for the block. Indicate if the
            // block terminates an atomic region and establish the transfer of control to
            // the next block(s) or out of the method.

            if ((ZingCompilerOptions.IsPreemtive && !block.MiddleOfTransition && !block.IsReturn) || (block.Yields))
            {
                // p.MiddleOfTransition = false;
                blockMethod.Body.Statements.Add(
                    new ExpressionStatement(
                        new AssignmentExpression(
                            new AssignmentStatement(
                                new QualifiedIdentifier(Identifier.For("p"), Identifier.For("MiddleOfTransition")),
                                new Literal(false, SystemTypes.Boolean)
                            )
                        )
                    )
                );
            }

            // p.AtomicityLevel = this.SavedAtomicityLevel + X;
            blockMethod.Body.Statements.Add(
                new ExpressionStatement(
                    new AssignmentExpression(
                        new AssignmentStatement(
                            new QualifiedIdentifier(Identifier.For("p"), Identifier.For("AtomicityLevel")),
                            new BinaryExpression(
                                new QualifiedIdentifier(new This(), Identifier.For("SavedAtomicityLevel")),
                                new Literal(block.RelativeAtomicLevel, SystemTypes.Int32),
                                NodeType.Add
                            )
                        )
                    )
                )
            );

            #if false
            //
            // The following code was added for summarization, but isn't quite right. It
            // updates the nextBlock too early for some blocks. -- Tony
            //
            //
            // when generating summaries of type MaxCall, we need to
            // know the value of nextBlock before we invoke p.Call().
            // the first of the two basic blocks of a Zing method call
            // is guaranteed to fall through, so we only need to lift
            // the assignment of nextBlock for fall-through blocks.
            if (block.ConditionalTarget == null && block.UnconditionalTarget != null)
            {
                stmt = Templates.GetStatementTemplate("UnconditionalBlockTransfer");
                Replacer.Replace(stmt, "_UnconditionalBlock",
                                 new Identifier(block.UnconditionalTarget.Name));
                blockMethod.Body.Statements.Add(stmt);
            }
            #endif

            if (block.Attributes != null)
            {
                Duplicator duplicator = new Duplicator(null, null);

                for (int i = 0, n = block.Attributes.Count; i < n; i++)
                {
                    if (block.Attributes[i] == null)
                        continue;

                    AttributeNode dupAttr = duplicator.VisitAttributeNode(block.Attributes[i]);

                    Normalizer normalizer = new Normalizer(false);
                    ExpressionList attrParams = normalizer.VisitExpressionList(dupAttr.Expressions);

                    // application.Trace(_context, _contextAttr, new Z.Attributes._attrName(...) );
                    ExpressionStatement traceStmt = new ExpressionStatement(
                        new MethodCall(
                            new QualifiedIdentifier(Identifier.For("application"), Identifier.For("Trace")),
                            new ExpressionList(
                                SourceContextConstructor(dupAttr.SourceContext),
                                new Literal(null, SystemTypes.Object),
                                new Construct(
                                    new MemberBinding(
                                        null,
                                        new TypeExpression(
                                            new QualifiedIdentifier(
                                                new QualifiedIdentifier(Identifier.For("Z"), Identifier.For("Attributes")),
                                                dupAttr.Type.Name
                                            )
                                        )
                                    ),
                                    attrParams
                                )
                            )
                        )
                    );
                    blockMethod.Body.Statements.Add(traceStmt);
                }
            }

            if (block.Statement != null)
            {
                if (block.SkipNormalizer)
                    blockMethod.Body.Statements.Add(block.Statement);
                else
                {
                    // Do statement-level code-gen pass on the block's statement
                    Normalizer normalizer = new Normalizer(this, block.Attributes, block.SecondOfTwo);

                    blockMethod.Body.Statements.Add((Statement)normalizer.Visit(block.Statement));
                }
            }

            if (block.ConditionalTarget != null && block.ConditionalExpression != null)
            {
                Block trueBlock, falseBlock;

                // if (_conditionalExpression)
                //     nextBlock = Blocks._conditionalTarget;
                // else
                //     nextBlock = Blocks._unconditionalTarget;
                blockMethod.Body.Statements.Add(
                    new If(
                        block.ConditionalExpression,
                        trueBlock = new Block(new StatementList(
                            new ExpressionStatement(
                                new AssignmentExpression(
                                    new AssignmentStatement(
                                        Identifier.For("nextBlock"),
                                        new QualifiedIdentifier(
                                            Identifier.For("Blocks"),
                                            Identifier.For(block.ConditionalTarget.Name)
                                        )
                                    )
                                )
                            )
                        )),
                        falseBlock = new Block(new StatementList(
                            new ExpressionStatement(
                                new AssignmentExpression(
                                    new AssignmentStatement(
                                        Identifier.For("nextBlock"),
                                        new QualifiedIdentifier(
                                            Identifier.For("Blocks"),
                                            Identifier.For(block.UnconditionalTarget.Name)
                                        )
                                    )
                                )
                            )
                        ))
                    )
                );

                AddScopeCleanupCalls(trueBlock.Statements, block, block.ConditionalTarget, nonTrivialScopes);
                AddScopeCleanupCalls(falseBlock.Statements, block, block.UnconditionalTarget, nonTrivialScopes);
            }
            else if (block.UnconditionalTarget != null)
            {
                // nextBlock = Blocks.X;
                blockMethod.Body.Statements.Add(
                    new ExpressionStatement(
                        new AssignmentExpression(
                            new AssignmentStatement(
                                Identifier.For("nextBlock"),
                                new QualifiedIdentifier(Identifier.For("Blocks"), Identifier.For(block.UnconditionalTarget.Name))
                            )
                        )
                    )
                );
                AddScopeCleanupCalls(blockMethod.Body.Statements, block, block.UnconditionalTarget, nonTrivialScopes);
            }
            else if (block.IsReturn)
            {
                Debug.Assert(block.UnconditionalTarget == null);

                Statement returnCall = Templates.GetStatementTemplate("ReturnBlockTransfer");
                SourceContext context;
                Return ret = block.Statement as Return;
                if (ret != null)
                {
                    context = ret.SourceContext;
                }
                else
                {
                    // If not a return stmt, the context is the closing brace of the method
                    context = zMethod.SourceContext;
                    context.StartPos = context.EndPos - 1;
                }

                Replacer.Replace(returnCall, "_context", SourceContextConstructor(context));
                Replacer.Replace(returnCall, "_contextAttr", ContextAttributeConstructor(block.Attributes));

                blockMethod.Body.Statements.Add(returnCall);

                // StateImpl.IsReturn = true;
                blockMethod.Body.Statements.Add(
                    new ExpressionStatement(
                        new AssignmentExpression(
                            new AssignmentStatement(
                                new QualifiedIdentifier(Identifier.For("StateImpl"), Identifier.For("IsReturn")),
                                new Literal(true, SystemTypes.Boolean)
                            )
                        )
                    )
                );
            }
        }
Example #26
0
        public static SymbolicBlock ExecBlockDown(Block b, SymbolicStore gammaIntoBlock, out SymbolicStore gammaOutOfBlock)
        {
            var duper = new Duplicator();
            var sb    = new SymbolicBlock(b);

            SymbolicStore gammaIntoCmd = gammaIntoBlock;

            foreach (Cmd c in b.Cmds)
            {
                var sc = new SymbolicCmd(c);
                if (c is AssumeCmd)
                {
                    if (!((AssumeCmd)c).Expr.Equals(Expr.True))
                    {
                        var tmp = ((AssumeCmd)c).Expr;
                        sc.AddCons(((AssumeCmd)c).Expr);
                    }
                }
                else if (c is AssignCmd)
                {
                    SymbolicStore newGamma; //= new SymbolicStore(gammaIntoCmd);

                    AssignCmd assgn = c as AssignCmd;
                    if (assgn.Lhss.Count != assgn.Rhss.Count)
                    {
                        Console.WriteLine("Bizzare: uneven assignment command in ExecDown");
                        continue;
                    }
                    //each AssignCmd contains a list of assignments
                    for (int i = 0; i < assgn.Lhss.Count; i++)
                    {
                        var lhsrhs = StoreLhs.Make(assgn.Lhss[i], assgn.Rhss[i]);
                        var lhs    = lhsrhs.fst;
                        var rhs    = lhsrhs.snd;

                        Expr oldrhs;
                        gammaIntoCmd.TryGetValue(lhs, out oldrhs);

                        //if lhs was uninitialized, we just add the new binding to the old gamma
                        if (oldrhs == null)
                        {
                            newGamma = new SymbolicStore(gammaIntoCmd);
                            newGamma.Add(lhs, rhs);
                        }
                        //otherwise we have to do substitution over everything
                        else
                        {
                            newGamma = new SymbolicStore();
                            newGamma.Add(lhs, Substituter.Apply(x => (x == lhs.Var) ? duper.VisitExpr(oldrhs) : null, rhs));

                            //otherwise, we need to substitute the old value for lhs into Gamma
                            foreach (var entry in gammaIntoCmd)
                            {
                                if (!entry.Key.Equals(lhs))
                                {
                                    newGamma.Add(entry.Key, Substituter.Apply(x => (x == lhs.Var) ? duper.VisitExpr(oldrhs) : null, entry.Value));
                                }
                            }
                        }
                        gammaIntoCmd = newGamma;
                        sc.AddGamma(newGamma);
                    }
                }
                else if (c is HavocCmd)
                {
                    Log.Out(Log.Warning, "Help! HavocCmd in ExecBlockDown!");
                }

                // if(sc.Gammas.Count != 0)
                sb.SCmds.Add(sc);
            }

            gammaOutOfBlock = gammaIntoCmd;
            return(sb);
        }
Example #27
0
      public Method methodToInferPostFrom = null;  //if set, Visit tries to infer a postcondition for method. 

      public override StatementList VisitStatementList(StatementList statements) {
        if (statements == null) return null;
        foreach (Statement stat in statements) {
          Return r = stat as Return;
          if (r != null && r.Expression != null) { //Statement return E; found. Test admissibility of E as a witness.
            WitnessFromCodeAdmissibilityVisitor admis = new WitnessFromCodeAdmissibilityVisitor();            
            try {
              admis.VisitExpression(r.Expression);
              this.Witnesses.Add(r.Expression); //witness found, otherwise exception would have been thrown
              
              #region add inferred postconditions if needed
              TypeNode retType = (methodToInferPostFrom == null || methodToInferPostFrom.ReturnType == null) ? null : methodToInferPostFrom.ReturnType;              
              if (r == statements[0] && retType != null && (retType.IsObjectReferenceType || retType.IsPrimitiveComparable)) {
                //the return statement is the first statement of the body.
                //We would like to add ensures result == r.Expression; However, we have to be careful, for 2 reasons.
                //1: == cannot be applied to structs and generic types. Note that we already tested that we do not return a struct.
                //2: result might be the implicitly boxed version of r.Expression (e.g., public object m() {returns 5;}), in which case result == r.Expression does not hold (in particular at runtime)
                //To account for 2, we have to box/unbox result and r.Expression as necessary
                //If r.Expression is a generic type, we have to distinguish cases !(r.Expression is System.ValueType) or (r.Expression is int) and act accordingly                              
                //(We do not (yet) support cases where r.Expression is a valueType other than an int, but they could be handled along the same lines.)

                if (methodToInferPostFrom.Contract == null) {
                  methodToInferPostFrom.Contract = new MethodContract(methodToInferPostFrom);
                }
                SourceContext scInferred = methodToInferPostFrom.Name.SourceContext; //can't set the sourcetext, so error message will be confusing...but then again, the idea is that this can never crash                                                                                
                
                //Duplicate the return expression to avoid sharing problems 
                Duplicator dup = new Duplicator(this.methodToInferPostFrom.DeclaringType.DeclaringModule, this.methodToInferPostFrom.DeclaringType);
                Expression returnInEq = dup.VisitExpression(r.Expression);

                //needed for casting/boxing/unboxing
                MemberBinding intType = new MemberBinding(null, SystemTypes.Int32);
                Literal objectLit = new Literal(SystemTypes.Object, SystemTypes.Type);
                Literal intLit = new Literal(SystemTypes.Int32, SystemTypes.Type);

                Expression resultBinding = new ReturnValue(methodToInferPostFrom.ReturnType, scInferred);
                Expression resultInEq = resultBinding;
                if (r.Expression.NodeType == NodeType.Box) { //if the return expression has been (implicitly) boxed, unbox both it and result
                  returnInEq = (returnInEq as BinaryExpression).Operand1; //as we have the return expression in hand, unboxing is easy
                  //adjust resultInEq to (returnInEq.Type)resultInEq (i.e., add an unbox), using an explicit coercion
                  BinaryExpression resultUnboxed = new BinaryExpression(resultInEq, intType, NodeType.Unbox, SystemTypes.Int32.GetReferenceType(), scInferred); //gets type System.Int32@ 
                  AddressDereference resultDeref = new AddressDereference(resultUnboxed, returnInEq.Type, scInferred);
                  resultInEq = new BinaryExpression(resultDeref, intLit, NodeType.ExplicitCoercion, SystemTypes.Int32, scInferred);
                }
                                
                if (returnInEq.Type != null && (returnInEq.Type.IsObjectReferenceType || returnInEq.Type.IsPrimitiveComparable)) {
                  //returnInEq is not a user-defined struct (to which we can't apply ==)
                  Expression eq = null; //holds the postcondition that is added
                  if (!(isGenericTypeThatCanBeStruct(returnInEq.Type))) {
                    //== can be applied to returnInEq. Therefore, it can also be applied to resultInEq, which is of a supertype (i.e., not generic type, not a struct). 
                    eq = new BinaryExpression(resultInEq, returnInEq, NodeType.Eq, SystemTypes.Boolean, scInferred);
                  } else {
                    #region adjust eq to compensate for generics 
                    //insert  ensures !(returnInEq is System.ValueType) ==> (object)resultInEq == (object)returnInEq;
                    //and     ensures returnInEq is int ==> (int)(object)resultInEq == (int)(object)returnInEq;
                    //the cast to object is needed to allow application of == and the cast to int. 
                    //Note that resultInEq.Type is known to also be a generic type as it is a supertype.
                    //(and note that in this case, there was no unboxing)

                    #region set up the antecedent !(returnInEq is System.ValueType)
                    TypeNode theType = SystemTypes.ValueType;

                    //antecedent: !(r.Expression is System.ValueType)
                    Expression ante = new BinaryExpression(r.Expression, new Literal(theType, SystemTypes.Type), NodeType.Is, SystemTypes.Boolean, scInferred);
                    ante = new UnaryExpression(ante, NodeType.LogicalNot, SystemTypes.Boolean, scInferred);
                    #endregion

                    #region adjust resultInEq and returnInEq to (object)resultInEq and (object)returnInEq
                    //adjust resultInEq to (object)result, so that it can be used in ==
                    //that means Box it to T, then ExplicitCast it to Object.
                    MemberBinding boxType = new MemberBinding(null, returnInEq.Type); //could also use method return type
                    BinaryExpression resultBoxed = new BinaryExpression(resultBinding, boxType, NodeType.Box, returnInEq.Type, scInferred);
                    resultInEq = new BinaryExpression(resultBoxed, objectLit, NodeType.ExplicitCoercion, SystemTypes.Object, scInferred);
                    
                    //adjust returnInEq to (object)returnInEq                    
                    BinaryExpression returnBoxed = new BinaryExpression(returnInEq, boxType, NodeType.Box, returnInEq.Type, scInferred);
                    returnInEq = new BinaryExpression(returnBoxed, objectLit, NodeType.ExplicitCoercion, SystemTypes.Object, scInferred);
                    #endregion

                    //Add first ensures; ensures ante ==> resultInEq == returnInEq;
                    eq = new BinaryExpression(resultInEq, returnInEq, NodeType.Eq, SystemTypes.Boolean, scInferred);
                    Expression impl = new BinaryExpression(ante, eq, NodeType.Implies, scInferred);
                    EnsuresNormal firstPost = new EnsuresNormal(impl);
                    firstPost.SourceContext = scInferred;
                    methodToInferPostFrom.Contract.Ensures.Add(firstPost);

                    //Now add ensures returnInEq is int ==> (int)(object)resultInEq == (int)(object)returnInEq;
                    //antecedent: r.Expression is int                
                    Expression secondAnte = new BinaryExpression(r.Expression, intLit, NodeType.Is, SystemTypes.Boolean, scInferred);

                    #region adjust resultInEq and returnInEq to (int)resultInEq and (int)returnInEq
                    //set resultInSecondEq to (int)resultInEq, i.e., to (int)(object)result
                    //this requires an unbox to int32@, then an adress-deref to int32, then an explicitcast to int32
                    //note that if we unbox to type Int32 directly, we get a "operation could destabilize the runtime" warining from the checkin tests
                    BinaryExpression resultUnboxed = new BinaryExpression(resultInEq, intType, NodeType.Unbox, SystemTypes.Int32.GetReferenceType(), scInferred); //gets type System.Int32@ 
                    AddressDereference resultDeref = new AddressDereference(resultUnboxed, SystemTypes.Int32, scInferred);
                    BinaryExpression resultInSecondEq = new BinaryExpression(resultDeref, intLit, NodeType.ExplicitCoercion, SystemTypes.Int32, scInferred);

                    //adjust returnInEq to (int)returnInEq 
                    BinaryExpression returnUnboxed = new BinaryExpression(returnInEq, intType, NodeType.Unbox, SystemTypes.Int32.GetReferenceType(), scInferred);
                    AddressDereference returnDeref = new AddressDereference(returnUnboxed, SystemTypes.Int32, scInferred);
                    BinaryExpression returnInSecondEq = new BinaryExpression(returnDeref, intLit, NodeType.ExplicitCoercion, SystemTypes.Int32, scInferred);
                    #endregion
                    
                    Expression secondEq = new BinaryExpression(resultInSecondEq, returnInSecondEq, NodeType.Eq, SystemTypes.Boolean, scInferred);
                    eq = new BinaryExpression(secondAnte, secondEq, NodeType.Implies, SystemTypes.Boolean, scInferred); //(Ab)use eq to hold the implication 
                    #endregion
                  }
                  //Add the constructed equality as a postcondition.
                  EnsuresNormal newPost = new EnsuresNormal(eq);
                  newPost.SourceContext = scInferred;
                  methodToInferPostFrom.Contract.Ensures.Add(newPost);  
                } //else don't generate a postcondition, can't apply == to a user-defined struct                 
              }
              #endregion
            }
            catch (ApplicationException e) { ApplicationException dumme = e; } //witness not admissible ('using' e to avoid warning)           
          }
        }
        return statements;
      }
Example #28
0
        /// <summary>
        /// Starting from the 0-index "split_here" annotation in begin, verifies until it reaches a subsequent "split_here" annotation
        /// Returns a list of blocks where all code not verified has asserts converted into assumes
        /// </summary>
        /// <param name="blocks">Implementation's collection of blocks</param>
        /// <param name="begin">Block containing the first split_here from which to start verifying</param>
        /// <param name="beginSplitId">0-based ID of the "split_here" annotation within begin at which to start verifying</param>
        /// <param name="blockInternalSplit">True if the entire split is contained within block begin</param>
        /// <param name="endPoints">Set of all blocks containing a "split_here" annotation</param>
        /// <returns></returns>
        // Note: Current implementation may over report errors.
        //       For example, if the control flow graph is a diamond (e.g., A -> B, C, B->D, C->D),
        //       and there is a split in B and an error in D, then D will be verified twice and hence report the error twice.
        //       Best solution may be to memoize blocks that have been fully verified and be sure not to verify them again
        private static List <Block> DoManualSplit(List <Block> blocks, Block begin, int beginSplitId,
                                                  bool blockInternalSplit, IEnumerable <Block> endPoints)
        {
            // Compute the set of blocks reachable from begin but not included in endPoints.  These will be verified in their entirety.
            var blocksToVerifyEntirely = new HashSet <Block>();
            var reachableEndPoints     =
                new HashSet <Block>(); // Reachable end points will be verified up to their first split point
            var todo = new Stack <Block>();

            todo.Push(begin);
            while (todo.Count > 0)
            {
                var currentBlock = todo.Pop();
                if (blocksToVerifyEntirely.Contains(currentBlock))
                {
                    continue;
                }
                blocksToVerifyEntirely.Add(currentBlock);
                var exit = currentBlock.TransferCmd as GotoCmd;
                if (exit != null)
                {
                    foreach (Block targetBlock in exit.labelTargets)
                    {
                        if (!endPoints.Contains(targetBlock))
                        {
                            todo.Push(targetBlock);
                        }
                        else
                        {
                            reachableEndPoints.Add(targetBlock);
                        }
                    }
                }
            }

            blocksToVerifyEntirely.Remove(begin);

            // Convert assumes to asserts in "unreachable" blocks, including portions of blocks containing "split_here"
            var newBlocks        = new List <Block>(blocks.Count()); // Copies of the original blocks
            var duplicator       = new Duplicator();
            var oldToNewBlockMap =
                new Dictionary <Block, Block>(blocks.Count()); // Maps original blocks to their new copies in newBlocks

            foreach (var currentBlock in blocks)
            {
                var newBlock = (Block)duplicator.VisitBlock(currentBlock);
                oldToNewBlockMap[currentBlock] = newBlock;
                newBlocks.Add(newBlock);

                if (!blockInternalSplit && blocksToVerifyEntirely.Contains(currentBlock))
                {
                    continue; // All reachable blocks must be checked in their entirety, so don't change anything
                }
                // Otherwise, we only verify a portion of the current block, so we'll need to look at each of its commands

                // !verify -> convert assert to assume
                var verify =
                    (currentBlock == begin &&
                     beginSplitId == -1
                    ) || // -1 tells us to start verifying from the very beginning (i.e., there is no split in the begin block)
                    (
                        reachableEndPoints
                        .Contains(currentBlock) && // This endpoint is reachable from begin, so we verify until we hit the first split point
                        !blockInternalSplit); // Don't bother verifying if all of the splitting is within the begin block
                var newCmds        = new List <Cmd>();
                var splitHereCount = 0;

                foreach (Cmd c in currentBlock.Cmds)
                {
                    var p = c as PredicateCmd;
                    if (p != null && QKeyValue.FindBoolAttribute(p.Attributes, "split_here"))
                    {
                        if (currentBlock == begin)
                        {
                            // Verify everything between the beginSplitId we were given and the next split
                            if (splitHereCount == beginSplitId)
                            {
                                verify = true;
                            }
                            else if (splitHereCount == beginSplitId + 1)
                            {
                                verify = false;
                            }
                        }
                        else
                        {
                            // We're in an endpoint so we stop verifying as soon as we hit a "split_here"
                            verify = false;
                        }

                        splitHereCount++;
                    }

                    var asrt = c as AssertCmd;
                    if (verify || asrt == null)
                    {
                        newCmds.Add(c);
                    }
                    else
                    {
                        newCmds.Add(VCGen.AssertTurnedIntoAssume(asrt));
                    }
                }

                newBlock.Cmds = newCmds;
            }

            // Patch the edges between the new blocks
            foreach (var oldBlock in blocks)
            {
                if (oldBlock.TransferCmd is ReturnCmd)
                {
                    continue;
                }

                var gotoCmd         = (GotoCmd)oldBlock.TransferCmd;
                var newLabelTargets = new List <Block>(gotoCmd.labelTargets.Count());
                var newLabelNames   = new List <string>(gotoCmd.labelTargets.Count());
                foreach (var target in gotoCmd.labelTargets)
                {
                    newLabelTargets.Add(oldToNewBlockMap[target]);
                    newLabelNames.Add(oldToNewBlockMap[target].Label);
                }

                oldToNewBlockMap[oldBlock].TransferCmd = new GotoCmd(gotoCmd.tok, newLabelNames, newLabelTargets);
            }

            return(newBlocks);
        }
        public DuplicatorForContractsAndClosures(Module module, Method sourceMethod, Method targetMethod,
                                                 ContractNodes contractNodes, bool mapParameters)
            : base(module, targetMethod.DeclaringType)
        {
            this.sourceMethod = sourceMethod;
            this.targetMethod = targetMethod;

            this.RemoveNameForLocals = true;

            Duplicator dup = this;

            if (mapParameters)
            {
                if (sourceMethod.ThisParameter != null)
                {
                    if (targetMethod.ThisParameter != null)
                    {
                        dup.DuplicateFor[sourceMethod.ThisParameter.UniqueKey] = targetMethod.ThisParameter;
                    }
                    else
                    {
                        // target is a static wrapper. But duplicator cannot handle This -> Parameter conversion
                        // so we handle it explicitly here in this visitor.
                        replaceThisWithParameter = targetMethod.Parameters[0];
                    }
                }

                if (sourceMethod.Parameters != null && targetMethod.Parameters != null &&
                    sourceMethod.Parameters.Count == targetMethod.Parameters.Count)
                {
                    for (int i = 0, n = sourceMethod.Parameters.Count; i < n; i++)
                    {
                        dup.DuplicateFor[sourceMethod.Parameters[i].UniqueKey] = targetMethod.Parameters[i];
                    }
                }

                // This code makes sure that generic method parameters used by contracts inherited from contract class
                // are correctly replaced by the one defined in the target method.
                // Without this mapping <c>CheckPost</c> method in generated async closure class would contain an invalid
                // reference to a generic contract method parameter instead of generic async closure type parameter.
                // For more about this problem see comments for Microsoft.Contracts.Foxtrot.EmitAsyncClosure.GenericTypeMapper class
                // and issue #380.
                if (sourceMethod.TemplateParameters != null && targetMethod.TemplateParameters != null &&
                    sourceMethod.TemplateParameters.Count == targetMethod.TemplateParameters.Count)
                {
                    for (int i = 0, n = sourceMethod.TemplateParameters.Count; i < n; i++)
                    {
                        dup.DuplicateFor[sourceMethod.TemplateParameters[i].UniqueKey] = targetMethod.TemplateParameters[i];
                    }
                }
            }

            var originalType = HelperMethods.IsContractTypeForSomeOtherType(sourceMethod.DeclaringType, contractNodes);

            if (originalType != null)
            {
                var contractType = this.contractClass = sourceMethod.DeclaringType;
                while (contractType.Template != null)
                {
                    contractType = contractType.Template;
                }

                while (originalType.Template != null)
                {
                    originalType = originalType.Template;
                }

                // forward ContractType<A,B> -> originalType<A',B'>
                this.contractClassToForward = contractType;
                this.targetTypeToForwardTo  = originalType;

                //dup.DuplicateFor[contractType.UniqueKey] = originalType;
            }
        }
Example #30
0
        public void Save(string action = "")
        {
            using (var scope = new TransactionScope())
            {
                if (Id == Guid.Empty)
                {
                    Id                 = Guid.NewGuid();
                    CreateTime         = DateTime.Now;
                    LastUpdateTime     = DateTime.Now;
                    CreateUserAccount  = ClientCookie.UserCode;
                    CreateUserNameZHCN = ClientCookie.UserNameZHCN;
                    CreateUserNameENUS = ClientCookie.UserNameENUS;
                    IsHistory          = false;
                    Add(this);
                }
                else
                {
                    LastUpdateTime = DateTime.Now;
                    Update(this);
                }
                if (ReinBasicInfo != null)
                {
                    var reinBasicInfo    = Duplicator.AutoCopy(ReinBasicInfo);
                    var oldreinBasicInfo = ReinvestmentBasicInfo.FirstOrDefault(e => e.ConsInfoID == Id);
                    if (oldreinBasicInfo != null)
                    {
                        reinBasicInfo.Id = oldreinBasicInfo.Id;
                    }
                    else
                    {
                        reinBasicInfo.Id = 0;
                    }
                    reinBasicInfo.ConsInfoID = Id;
                    reinBasicInfo.Save();

                    UpdateMajorLeaseInfo();
                }

                if (ReinCost != null)
                {
                    var reinCost = Duplicator.AutoCopy(ReinCost);
                    reinCost.Id         = new Guid();
                    reinCost.ConsInfoID = Id;

                    reinCost.Save();
                }

                if (WriteOff != null)
                {
                    var writeOff = Duplicator.AutoCopy(WriteOff);
                    writeOff.Id         = new Guid();
                    writeOff.ConsInfoID = Id;
                    writeOff.Save();
                }
                SaveApproveUsers(action);
                if (!action.Equals("Edit"))
                {
                    SaveComments(action);
                }

                UpdateAttachmentStatusByReinvenstmentType();
                scope.Complete();
            }
        }
Example #31
0
 public void Init()
 {
     d = new Duplicator();
 }
        public override Expression VisitOldExpression(OldExpression oldExpression)
        {
            if (this.topLevelClosureClass != null)
            {
                // In Closure ==> Create a field

                // Since we're within a closure, we can't create a local to hold the value of the old expression
                // but instead have to create a field for it. That field can be a member of the top-level
                // closure class since nothing mentioned in the old expression (except possibly for the
                // bound variables of enclosing quantifications) should be anything captured from
                // an inner anonymous delegate.

                // BUT, first we have to know if the old expression depends on any of the bound
                // variables of the closures in which it is located. If not, then we can implement
                // it as a scalar and just generate the assignment "closure_class.field := e" for
                // "Old(e)" to take a snapshot of e's value in the prestate. If it does depend on
                // any of the bound variables, then we need to generate a set of for-loops that
                // compute the indices and values of e for each tuple of indices so it can be retrieved
                // (given the indices) in the post-state.
                CollectBoundVariables cbv = new CollectBoundVariables(this.stackOfBoundVariables);
                cbv.VisitExpression(oldExpression.expression);

                SubstituteClosureClassWithinOldExpressions subst = new SubstituteClosureClassWithinOldExpressions(this.closureLocals);
                Expression e = subst.VisitExpression(oldExpression.expression);
                if (cbv.FoundVariables.Count == 0)
                {
                    // Use a scalar for the old variable

                    Local closureLocal;
                    if (!this.closureLocals.TryGetValue(this.topLevelClosureClass, out closureLocal))
                    {
                        Contract.Assume(false, "can't find closure local!");
                    }

                    // Define a scalar

                    var   clTemplate = HelperMethods.Unspecialize(this.topLevelClosureClass);
                    Field f          = new Field(clTemplate,
                                                 null,
                                                 FieldFlags.CompilerControlled | FieldFlags.Public,
                                                 Identifier.For("_old" + oldExpression.expression.UniqueKey.ToString()),
                                                 // unique name for this old expr.
                                                 oldExpression.Type,
                                                 null);

                    clTemplate.Members.Add(f);

                    // now produce properly instantiated field
                    f = (Field)Rewriter.GetMemberInstanceReference(f, this.topLevelClosureClass);

                    // Generate code to store value in prestate

                    this.prestateValuesOfOldExpressions.Statements.Add(
                        new AssignmentStatement(new MemberBinding(closureLocal, f), e));

                    // Return expression to be used in poststate

                    // Return an expression that will evaluate in the poststate to the value of the old
                    // expression in the prestate. This will be this.up.f where "up" is the field C#
                    // generated to point to the instance of the top-level closure class.
                    if (this.PointerToTopLevelClosureClass == null)
                    {
                        // then the old expression occurs in the top-level closure class. Just return "this.f"
                        // where "this" refers to the top-level closure class.
                        return(new MemberBinding(new This(this.currentClosureClass), f));
                    }
                    else
                    {
                        return(new MemberBinding(
                                   new MemberBinding(new This(this.currentClosureClass), this.PointerToTopLevelClosureClass),
                                   f));
                    }
                }
                else
                {
                    // the Old expression *does* depend upon at least one of the bound variable
                    // in a ForAll or Exists expression

                    // Use an indexed variable for the old variable

                    TypeNode oldVariableTypeDomain;

                    // Decide if domain is one-dimensional or not

                    bool oneDimensional = cbv.FoundVariables.Count == 1 && cbv.FoundVariables[0].Type.IsValueType;
                    if (oneDimensional)
                    {
                        // a one-dimensional old-expression can use the index variable directly
                        oldVariableTypeDomain = cbv.FoundVariables[0].Type;
                    }
                    else
                    {
                        oldVariableTypeDomain = SystemTypes.GenericList.GetTemplateInstance(this.module,
                                                                                            SystemTypes.Int32);
                    }

                    TypeNode oldVariableTypeRange = oldExpression.Type;
                    TypeNode oldVariableType      = SystemTypes.GenericDictionary.GetTemplateInstance(this.module,
                                                                                                      oldVariableTypeDomain, oldVariableTypeRange);

                    Local closureLocal;
                    if (!this.closureLocals.TryGetValue(this.topLevelClosureClass, out closureLocal))
                    {
                        Contract.Assume(false, "can't find closure local");
                    }

                    // Define an indexed variable

                    var clTemplate = HelperMethods.Unspecialize(this.topLevelClosureClass);

                    Field f = new Field(clTemplate,
                                        null,
                                        FieldFlags.CompilerControlled | FieldFlags.Assembly,
                                        // can't be private or protected because it needs to be accessed from inner (closure) classes that don't inherit from the class this field is added to.
                                        Identifier.For("_old" + oldExpression.expression.UniqueKey.ToString()),
                                        // unique name for this old expr.
                                        oldVariableType,
                                        null);

                    clTemplate.Members.Add(f);

                    // instantiate f
                    f = (Field)Rewriter.GetMemberInstanceReference(f, closureLocal.Type);

                    // Generate code to initialize the indexed variable

                    Statement init = new AssignmentStatement(
                        new MemberBinding(closureLocal, f),
                        new Construct(new MemberBinding(null, oldVariableType.GetConstructor()), null));

                    this.prestateValuesOfOldExpressions.Statements.Add(init);

                    // Generate code to store values in prestate

                    // Create assignment: this.closure.f[i,j,k,...] = e;

                    Method setItem = oldVariableType.GetMethod(Identifier.For("set_Item"), oldVariableTypeDomain, oldVariableTypeRange);

                    Expression index;
                    if (oneDimensional)
                    {
                        index = cbv.FoundVariables[0];
                    }
                    else
                    {
                        //InstanceInitializer ctor =
                        //  ContractNodes.TupleClass.GetConstructor(SystemTypes.Int32.GetArrayType(1));
                        //Expression index = new Construct(new MemberBinding(null,ctor),new ExpressionList(
                        index = Literal.Null;
                    }

                    MethodCall mc = new MethodCall(new MemberBinding(new MemberBinding(closureLocal, f), setItem),
                                                   new ExpressionList(index, e));

                    Statement stat = new ExpressionStatement(mc);

                    List <Local>     locals   = new List <Local>(this.stackOfBoundVariables.Count);
                    TrivialHashtable paramMap = new TrivialHashtable();

                    // Generate a local for each bound variable to use in for-loop

                    foreach (Variable v in this.stackOfBoundVariables)
                    {
                        Local l = new Local(Identifier.Empty, v.Type);
                        paramMap[v.UniqueKey] = l;
                        locals.Add(l);
                    }

                    // Substitute locals for bound variables in old expression *AND* in inner loop bounds

                    SubstituteParameters sps = new SubstituteParameters(paramMap, this.stackOfBoundVariables);
                    sps.Visit(stat);

                    // Create nested for-loops around assignment

                    // keep track of when the first variable is used (from innermost to outermost)
                    // as soon as the first one is needed because the old expression depends on it,
                    // then keep all enclosing loops. It would be possible to keep only those where
                    // the necessary loops have loop bounds that depend on an enclosing loop, but I
                    // haven't calculated that, so just keep them all. For instance, if the old expression
                    // depends on j and the loops are "for i,0,n" and inside that "for j,0,i", then need
                    // both loops. If the inner loop bounds were 0 and n, then wouldn't need the outer
                    // loop.
                    bool usedAVariable = false;

                    for (int i = this.stackOfBoundVariables.Count - 1; 0 <= i; i--)
                    {
                        if (!usedAVariable &&
                            !cbv.FoundVariables.Contains(this.stackOfBoundVariables[i]))
                        {
                            continue;
                        }
                        usedAVariable = true;
                        Expression lowerBound = new Duplicator(this.module, this.currentClosureClass).VisitExpression(
                            this.stackOfMethods[i].Operands[0]);

                        lowerBound = subst.VisitExpression(lowerBound);
                        lowerBound = sps.VisitExpression(lowerBound);

                        Expression upperBound = new Duplicator(this.module, this.currentClosureClass).VisitExpression(
                            this.stackOfMethods[i].Operands[1]);

                        upperBound = subst.VisitExpression(upperBound);
                        upperBound = sps.VisitExpression(upperBound);

                        stat = RewriteHelper.GenerateForLoop(locals[i], lowerBound, upperBound, stat);
                    }

                    this.prestateValuesOfOldExpressions.Statements.Add(stat);

                    // Return expression to be used in poststate

                    Method getItem = oldVariableType.GetMethod(Identifier.For("get_Item"), oldVariableTypeDomain);
                    if (oneDimensional)
                    {
                        index = cbv.FoundReferences[0];
                    }
                    else
                    {
                        //InstanceInitializer ctor =
                        //  ContractNodes.TupleClass.GetConstructor(SystemTypes.Int32.GetArrayType(1));
                        //Expression index = new Construct(new MemberBinding(null,ctor),new ExpressionList(
                        index = Literal.Null;
                    }

                    // Return an expression that will evaluate in the poststate to the value of the old
                    // expression in the prestate. This will be this.up.f[i,j,k,...] where "up" is the field C#
                    // generated to point to the instance of the top-level closure class.
                    MemberBinding thisDotF;

                    if (this.PointerToTopLevelClosureClass == null)
                    {
                        // then the old expression occurs in the top-level closure class. Just return "this.f"
                        // where "this" refers to the top-level closure class.
                        Contract.Assume(f != null);

                        thisDotF = new MemberBinding(new This(clTemplate), HelperMethods.Unspecialize(f));
                    }
                    else
                    {
                        thisDotF = new MemberBinding(
                            new MemberBinding(new This(clTemplate), this.PointerToTopLevelClosureClass),
                            f);
                    }

                    return(new MethodCall(new MemberBinding(thisDotF, getItem), new ExpressionList(index)));
                }
            }
            else
            {
                // Not in closure ==> Create a local variable

                Local l = GetLocalForOldExpression(oldExpression);

                // Make sure local can be seen in the debugger (for the entire method, unfortunately)

                if (currentMethod.LocalList == null)
                {
                    currentMethod.LocalList = new LocalList();
                }

                currentMethod.LocalList.Add(l);
                currentMethod.Body.HasLocals = true;

                this.prestateValuesOfOldExpressions.Statements.Add(new AssignmentStatement(l, oldExpression.expression));

                // Return an expression that will evaluate in the poststate to the value of the old
                // expression in the prestate. When we're not in a closure, this is just the local
                // itself.
                return(l);
            }
        }
        /// <summary>
        /// VRChatアバターインスタンスからVRMインスタンスへ変換します。
        /// </summary>
        /// <param name="instance">ヒエラルキー上のGameObject。</param>
        /// <param name="presetVRChatBindingPairs">各表情への割り当て。</param>
        internal static void Convert(
            string outputPath,
            GameObject instance,
            VRMMetaObject meta,
            IDictionary <ExpressionPreset, VRChatExpressionBinding> presetVRChatBindingPairs
            )
        {
            GameObject clone = null, normalized = null;

            try
            {
                var rootObjectName = instance.name;
                clone = Object.Instantiate(instance);

                // 非表示のオブジェクト・コンポーネントを削除
                // TODO: アクティブ・非アクティブの切り替えをシェイプキーに変換する
                VRChatToVRMConverter.RemoveInactiveObjectsAndDisabledComponents(clone);


                // 表情とシェイプキー名の組み合わせを取得
                var presetShapeKeyNameWeightPairsPairs = presetVRChatBindingPairs.ToDictionary(
                    presetVRChatBindingPair => presetVRChatBindingPair.Key,
                    presetVRChatBindingPair => VRChatExpressionsReplacer.ExtractShapeKeyNames(presetVRChatBindingPair.Value)
                    );

                // VRM設定1
                var temporaryFolder = UnityPath.FromUnityPath(VRChatToVRMConverter.TemporaryFolderPath);
                temporaryFolder.EnsureFolder();
                var temporaryPrefabPath = temporaryFolder.Child(VRChatToVRMConverter.TemporaryPrefabFileName).Value;
                VRMInitializer.Initialize(temporaryPrefabPath, clone);
                VRChatToVRMConverter.SetFirstPersonOffset(clone);
                VRChatToVRMConverter.SetLookAtBoneApplyer(clone);
                var sourceAndDestination = clone.GetComponent <Animator>();
                if (DynamicBones.IsImported())
                {
                    DynamicBonesToVRMSpringBonesConverter.Convert(
                        source: sourceAndDestination,
                        destination: sourceAndDestination
                        );
                    VRChatToVRMConverter.RemoveUnusedColliderGroups(clone);
                }

                // 正規化
                normalized = VRMBoneNormalizer.Execute(clone, forceTPose: true);

                // 全メッシュ結合
                var combinedRenderer = CombineMeshesAndSubMeshes.Combine(
                    normalized,
                    notCombineRendererObjectNames: new List <string>(),
                    destinationObjectName: "vrm-mesh",
                    savingAsAsset: false
                    );

                // 使用していないシェイプキーの削除
                SkinnedMeshUtility.CleanUpShapeKeys(combinedRenderer.sharedMesh, presetShapeKeyNameWeightPairsPairs
                                                    .SelectMany(presetShapeKeyNameWeightPairsPair => presetShapeKeyNameWeightPairsPair.Value.Keys)
                                                    .Distinct());

                // シェイプキーの分離
                Utilities.MeshUtility.SeparationProcessing(normalized);

                // マテリアルの設定・アセットとして保存
                VRChatToVRMConverter.ReplaceShaders(normalized, temporaryPrefabPath);

                // GameObject・メッシュなどをアセットとして保存 (アセットとして存在しないと正常にエクスポートできない)
                normalized.name = rootObjectName;
                var animator = normalized.GetComponent <Animator>();
                animator.avatar = Duplicator.CreateObjectToFolder(animator.avatar, temporaryPrefabPath);
                meta.name       = "Meta";
                normalized.GetComponent <VRMMeta>().Meta = Duplicator.CreateObjectToFolder(meta, temporaryPrefabPath);
                foreach (var renderer in normalized.GetComponentsInChildren <SkinnedMeshRenderer>())
                {
                    renderer.sharedMesh.name = renderer.name;
                    renderer.sharedMesh      = Duplicator.CreateObjectToFolder(renderer.sharedMesh, temporaryPrefabPath);
                }

                // VRM設定2
                VRChatToVRMConverter.SetFirstPersonRenderers(normalized);

                // 表情の設定
                VRChatExpressionsReplacer.SetExpressions(normalized, presetShapeKeyNameWeightPairsPairs);

                var prefab = PrefabUtility
                             .SaveAsPrefabAssetAndConnect(normalized, temporaryPrefabPath, InteractionMode.AutomatedAction);

                // エクスポート
                AssetDatabase.SaveAssets();
                File.WriteAllBytes(
                    outputPath,
                    VRMEditorExporter.Export(prefab, meta: null, ScriptableObject.CreateInstance <VRMExportSettings>())
                    );
            }
            catch (Exception exception)
            {
                ErrorDialog.Open(exception);
                throw;
            }
            finally
            {
                if (clone != null)
                {
                    Object.DestroyImmediate(clone);
                }
                if (normalized != null)
                {
                    Object.DestroyImmediate(normalized);
                }
                AssetDatabase.DeleteAsset("Assets/VRMConverterTemporary");
            }
        }
Example #34
0
        public override string Edit()
        {
            var taskUrl = string.Format("/Reimage/Main#/ConsInfo?projectId={0}", ProjectId);

            using (var scope = new TransactionScope())
            {
                var reimageInfo = ReimageInfo.FirstOrDefault(e => e.ProjectId.Equals(ProjectId));
                if (reimageInfo == null)
                {
                    throw new Exception("Could not find the Reimage Info, please check it!");
                }
                var task = reimageInfo.GenerateTaskWork(FlowCode.Reimage_ConsInfo,
                                                        "Reimage_ConsInfo",
                                                        "Reimage_ConsInfo",
                                                        taskUrl);
                task.ActivityName = NodeCode.Start;
                task.ActionName   = SetTaskActionName(ProjectId);
                TaskWork.Add(task);

                var package = ReimagePackage.GetReimagePackageInfo(ProjectId);
                if (package != null)
                {
                    package.CompleteActorPackageTask(reimageInfo.AssetActorAccount);
                }


                var attachments = Attachment.Search(e => e.RefTableID == Id.ToString() &&
                                                    e.RefTableName == WFReimageConsInfo.TableName).AsNoTracking().ToList();



                ProjectInfo.Reset(ProjectId, FlowCode.Reimage_ConsInfo);
                var wfEntity = GetWorkflowEntity(ProjectId, FlowCode.Reimage_Package);
                if (wfEntity != null)
                {
                    wfEntity.ChangePackageHoldingStatus(HoldingStatus.No);
                }



                var form = Duplicator.AutoCopy(this);
                form.Id         = Guid.Empty;
                form.ProcInstId = null;
                form.IsHistory  = false;
                form.Comments   = null;
                form.CreateTime = DateTime.Now;
                form.SaveEdit("edit");

                List <Attachment> listAttachment = new List <Attachment>();
                Mapper.CreateMap <Attachment, Attachment>();
                foreach (var attachment in attachments)
                {
                    var newAttachment = Duplicator.AutoCopy(attachment);
                    newAttachment.RefTableID = form.Id.ToString();
                    newAttachment.ID         = Guid.NewGuid();
                    listAttachment.Add(newAttachment);
                }
                Attachment.Add(listAttachment.ToArray());
                IsHistory = true;
                Update(this);
                scope.Complete();
            }

            return(taskUrl);
        }
        private void OnWizardCreate()
        {
            if (string.IsNullOrEmpty(this.destinationPath))
            {
                string sourcePath = this.GetAssetsPath(vrm: this.avatar.gameObject);
                this.destinationPath = UnityPath.FromUnityPath(sourcePath).Parent
                                       .Child(Path.GetFileNameWithoutExtension(sourcePath) + " (VRChat).prefab").Value;
            }
            else
            {
                UnityPath destinationFolderUnityPath = UnityPath.FromUnityPath(this.destinationPath).Parent;
                while (!destinationFolderUnityPath.IsDirectoryExists)
                {
                    destinationFolderUnityPath = destinationFolderUnityPath.Parent;
                }
                this.destinationPath = destinationFolderUnityPath.Child(Path.GetFileName(this.destinationPath)).Value;
            }

            string destinationPath = EditorUtility.SaveFilePanelInProject(
                "",
                Path.GetFileName(path: this.destinationPath),
                "prefab",
                "",
                Path.GetDirectoryName(path: this.destinationPath)
                );

            if (string.IsNullOrEmpty(destinationPath))
            {
                Wizard.Open(avatar: this.avatar.gameObject);
                return;
            }
            this.destinationPath = destinationPath;

            // プレハブ、およびシーン上のプレハブインスタンスのBlueprint IDを取得
            string prefabBlueprintId = "";
            var    blueprintIds      = new Dictionary <int, string>();
            var    previousPrefab    = AssetDatabase.LoadMainAssetAtPath(this.destinationPath) as GameObject;

            if (previousPrefab)
            {
                var pipelineManager = previousPrefab.GetComponent <PipelineManager>();
                prefabBlueprintId = pipelineManager ? pipelineManager.blueprintId : "";

                GameObject[] previousRootGameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
                blueprintIds = previousRootGameObjects
                               .Where(root => PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(root) == this.destinationPath)
                               .Select(root =>
                {
                    var manager     = root.GetComponent <PipelineManager>();
                    var blueprintId = manager ? manager.blueprintId : "";
                    return(new
                    {
                        index = Array.IndexOf(previousRootGameObjects, root),
                        blueprintId = blueprintId != prefabBlueprintId ? blueprintId : "",
                    });
                }).ToDictionary(
                    keySelector: indexAndBlueprintId => indexAndBlueprintId.index,
                    elementSelector: indexAndBlueprintId => indexAndBlueprintId.blueprintId
                    );
            }

            GameObject prefabInstance = Duplicator.Duplicate(
                sourceAvatar: this.avatar.gameObject,
                destinationPath: this.destinationPath,
                notCombineRendererObjectNames: this.notCombineRendererObjectNames,
                combineMeshesAndSubMeshes: this.combineMeshes
                );

            var messages = new List <Converter.Message>();

            if (this.forQuest)
            {
                messages.AddRange(Wizard.GenerateQuestLimitationsErrorMessages(prefab: prefabInstance));
            }

            this.SaveSettings();

            foreach (VRMSpringBone springBone in this.GetSpringBonesWithComments(prefab: prefabInstance, comments: this.excludedSpringBoneComments)
                     .SelectMany(springBone => springBone))
            {
                UnityEngine.Object.DestroyImmediate(springBone);
            }

            var clips = VRMUtility.GetAllVRMBlendShapeClips(avatar: this.avatar.gameObject);

            messages.AddRange(Converter.Convert(
                                  prefabInstance: prefabInstance,
                                  clips: clips,
                                  swayingObjectsConverterSetting: this.swayingObjects,
                                  takingOverSwayingParameters: this.takeOverSwayingParameters,
                                  swayingParametersConverter: this.swayingParametersConverter,
                                  enableAutoEyeMovement: this.enableEyeMovement,
                                  addedShouldersPositionY: this.shoulderHeights,
                                  moveEyeBoneToFrontForEyeMovement: this.moveEyeBoneToFrontForEyeMovement,
                                  forQuest: this.forQuest,
                                  addedArmaturePositionY: this.armatureHeight,
                                  useAnimatorForBlinks: this.useAnimatorForBlinks,
                                  useShapeKeyNormalsAndTangents: this.useShapeKeyNormalsAndTangents,
                                  vrmBlendShapeForFINGERPOINT: !string.IsNullOrEmpty(this.blendShapeForFingerpoint)
                    ? VRMUtility.GetUserDefinedBlendShapeClip(clips, this.blendShapeForFingerpoint) as VRMBlendShapeClip
                    : null
                                  ));

            // 変換前のプレハブのPipeline ManagerのBlueprint IDを反映
            if (!string.IsNullOrEmpty(prefabBlueprintId))
            {
                prefabInstance.GetComponent <PipelineManager>().blueprintId = prefabBlueprintId;
            }

            if (this.postConverting != null)
            {
                this.postConverting(prefabInstance, prefabInstance.GetComponent <VRMMeta>());
            }

            PrefabUtility.ApplyPrefabInstance(prefabInstance, InteractionMode.AutomatedAction);

            // 変換前のプレハブインスタンスのPipeline ManagerのBlueprint IDを反映
            GameObject[] rootGameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
            foreach (var(avatarIndex, blueprintId) in blueprintIds)
            {
                if (string.IsNullOrEmpty(blueprintId))
                {
                    continue;
                }
                rootGameObjects[avatarIndex].GetComponent <PipelineManager>().blueprintId = blueprintId;
            }

            if (blueprintIds.Count > 0)
            {
                // シーンのルートに、すでに他のプレハブインスタンスが存在していれば、変換用のインスタンスは削除
                UnityEngine.Object.DestroyImmediate(prefabInstance);
            }

            ResultDialog.Open(messages: messages);
        }
Example #36
0
    /// <summary>
    /// Implements the runtime check for invariants of class C. Also implements the runtime check for modelfields.
    /// ensures: If c declares invariants or modelfields, then c.Contract.InvariantMethod contains their runtime checking code; 
    /// Adds the CheckInvariant method to c.Members if it wasn't a member already.
    /// </summary>
    void ImplementCheckInvariantMethod(Class c) { // c is the class to which all of this code is going to get attached to.
      Method m = null;
      #region Get a handle m on the invariant method, create one if necessary      
      if (c.Contract == null || c.Contract.InvariantMethod == null) {
        Method invariantMethod = new Method(
          c,
          new AttributeList(),
          Identifier.For("SpecSharp::CheckInvariant"),
          new ParameterList(new Parameter(Identifier.For("throwException"), SystemTypes.Boolean)),
          SystemTypes.Boolean,
          null);
        invariantMethod.CallingConvention = CallingConventionFlags.HasThis;
        invariantMethod.Flags = MethodFlags.Private;
        m = invariantMethod;
      } else 
        m = c.Contract.InvariantMethod;
      #endregion Get a handle on the invariant method, create one if necessary

      StatementList stmts = new StatementList();
      #region Create code for all of the invariants, implicit and explicit. Add that code to stmts.
      Parameter throwException = m.Parameters[0];
      InvariantList consolidatedInvariants = new InvariantList();
      InvariantList invariants = c.Contract == null ? null : c.Contract.Invariants;
      for (int i = 0, n = invariants == null ? 0 : invariants.Count; i < n; i++)
        if (!invariants[i].IsStatic)
          consolidatedInvariants.Add(invariants[i]);
//      InterfaceList ifaces = this.GetTypeView(c).Interfaces;
      InterfaceList ifaces = c.Interfaces;
      for (int i = 0, n = ifaces.Count; i < n; i++){
        Interface iface = ifaces[i];
        if (iface == null) continue;
        GatherInheritedInstanceInvariants(iface, consolidatedInvariants);
      }

      for (int i = 0; i < consolidatedInvariants.Count; i++){
        Invariant inv = consolidatedInvariants[i];
        stmts.Add(new If(new UnaryExpression(inv.Condition, NodeType.LogicalNot, SystemTypes.Boolean),
          new Block(new StatementList(
            new If(throwException,
              new Block(new StatementList(
                new Throw(new Construct(new MemberBinding(null, SystemTypes.ObjectInvariantException.GetConstructor()), null, SystemTypes.ObjectInvariantException), inv.SourceContext)
              )),
              new Block(new StatementList(new Return(Literal.False)))))),
          null));
      }
      #endregion

      #region Create code for all of the modelfields defined by c. Add that code to stmts.
      StatementList mfStats = new StatementList();
      ExpressionList modifiesList = new ExpressionList();  // synthesize modifies clause
      foreach (ModelfieldContract mfC in c.Contract.ModelfieldContracts) {
        //Add the following code to the method:
        //  if (!E) {
        //    <mfC.Modelfield> = value(mfC.Witness);
        //    if (!E) throw exception;
        //  }
        //where E is the conjunction of (1) all satisfies clauses of the contract, and (2) all satisfies clauses of overridden contracts in superclasses.
        //Note that satisifes clauses of contracts implemented by mfC (i.e., contracts in interfaces) have been copied to mfC.
        //Note that if f in C overrides f in D, and f in D overrides f in E, then f in C overrides f in E.
        Expression E = Literal.True;
        for (ModelfieldContract currentMfC = mfC; currentMfC != null; currentMfC = currentMfC.NearestOverriddenContract) {
          foreach (Expression satClause in currentMfC.SatisfiesList) {
            if (satClause == null) continue;  //error will have been dealt with elsewhere             
            E = new BinaryExpression(satClause, E, NodeType.LogicalAnd, SystemTypes.Boolean);
          }
        }
        Expression notE = new UnaryExpression(E, NodeType.LogicalNot, SystemTypes.Boolean);
      
        #region create the if statement
        //Start with the creation of the body of the if.
        MemberBinding lhs = new MemberBinding(new This(c), mfC.Modelfield);
        Statement setF = new AssignmentStatement(lhs, mfC.Witness);
        modifiesList.Add(lhs);  // synthesize modifies clause
        String mfAsString = mfC.Modelfield.FullName;        
        MemberBinding exc = new MemberBinding(null,SystemTypes.ModelfieldException.GetConstructor(SystemTypes.String));
        Construct exception = new Construct(exc, new ExpressionList(new Literal(mfAsString,SystemTypes.String)), SystemTypes.ModelfieldException);
        Block innerIfBody = new Block(new StatementList(
          new If(throwException,
            new Block(new StatementList(
              new Throw(exception, mfC.Modelfield.SourceContext)
            )),
            new Block(new StatementList(new Return(Literal.False))))));        

        Statement innerIf = new If(notE, innerIfBody, null);
        StatementList body = new StatementList();
        body.Add(setF);
        body.Add(innerIf);          
        
        Statement outerIf = new If(notE, new Block(body), null);
        #endregion
        mfStats.Add(outerIf);
      }                                   
      #endregion
                                     
      #region If c declares invariants or modelfields, then add a contract to c if it has none, and make sure that m is c's InvariantMethod.
      if (stmts.Count > 0 || mfStats.Count > 0) {

        Duplicator dup = new Duplicator(this.currentModule, this.currentType);
        dup.DuplicateFor[throwException.UniqueKey] = throwException;
        stmts = dup.VisitStatementList(stmts);
        mfStats = dup.VisitStatementList(mfStats);        

        m.Body = new Block(stmts);
        m.Body.Statements.Add(new Block(mfStats)); //The model field code should be wrapped in a ContractMarkerException block, but I can't get it to work
        m.Body.Statements.Add(new Return(Literal.True));        
        
        m.Body.HasLocals = true;  //who knows? there might be locals in the invariants or model fields (quantifier bound variables).
        
        #region Slap on NoDefaultContract and (what is roughly the equivalent of) a requires this.PreValid. //I doubt if this is still needed
        //No need for a runtime check of this precondition though, so directly add an attribute.
        //Bit of a hack, but there does not seem to be a really good place to do this.        

        InstanceInitializer ndCtor = SystemTypes.NoDefaultContractAttribute.GetConstructor();
        if (ndCtor != null) 
          m.Attributes.Add(new AttributeNode(new MemberBinding(null, ndCtor), null, AttributeTargets.Method));        

        TypeNode guard = SystemTypes.Guard;
        if (guard != null) {
          Method method = guard.GetMethod(Identifier.For("FrameIsPrevalid"), SystemTypes.Object, SystemTypes.Type);
          if (method != null)
          {
              This t = new This(c);
              Expression req = new MethodCall(
                                new MemberBinding(null, method),
                                new ExpressionList(t, new UnaryExpression(new Literal(t.Type, SystemTypes.Type), NodeType.Typeof, OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type))));

              // Place it in the method contract so downstream tools that are in the compiler pipeline see it
              if (m.Contract == null)
              {
                  m.Contract = new MethodContract(m);
              }
              if (m.Contract.Requires == null)
              {
                  m.Contract.Requires = new RequiresList(1);
              }
              m.Contract.Requires.Add(new RequiresPlain(req));

              m.Contract.Modifies = modifiesList;  // needed for model fields


              // Since this happens after contracts are serialized, serialize the precondition and stick it in the method's attributes.
              ContractSerializer cs = new ContractSerializer(this.currentModule);
              cs.Visit(req);
              string val = cs.SerializedContract;
              InstanceInitializer ctor = SystemTypes.RequiresAttribute.GetConstructor(SystemTypes.String);
              MemberBinding attrBinding = new MemberBinding(null, ctor);
              ExpressionList args = new ExpressionList();
              args.Add(new Literal(val, SystemTypes.String));
              AttributeNode a = new AttributeNode(attrBinding, args, (AttributeTargets)0);
              m.Attributes.Add(a);

              if (modifiesList.Count > 0)
              {
                  ctor = SystemTypes.ModifiesAttribute.GetConstructor(SystemTypes.String);
                  for (int i = 0, n = modifiesList.Count; i < n; i++)
                  {
                      Expression e = modifiesList[i];
                      a = Checker.SerializeExpression(ctor, e, this.currentModule);
                      m.Attributes.Add(a);
                  }
              }
          }
        }

        #endregion
        
        if (c.Contract == null) {
          c.Contract = new TypeContract(c);
          c.Contract.DeclaringType = c;
        }
        if (c.Contract.InvariantMethod == null) {
          c.Contract.InvariantMethod = m;
          c.Members.Add(m);
        } //else assert (m == c.Contract.InvairantMethod)
      }
      #endregion           
    }
Example #37
0
    public override MethodContract VisitMethodContract(MethodContract contract){
      if (contract == null) return null;
      if (contract.DeclaringMethod == null) return contract;
      // No point normalizing contracts on interfaces; no code should be generated.
      if (contract.DeclaringMethod.DeclaringType is Interface) return contract;

      Duplicator duplicator = new Duplicator(this.currentModule, this.currentType);      
      MethodContract copy = duplicator.VisitMethodContract(contract);            

      if (this.currentMethod.IsVisibleOutsideAssembly
        ? !(this.currentCompilation != null && this.currentCompilation.CompilerParameters is CompilerOptions && ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableDefensiveChecks)
        : !(this.currentCompilation != null && this.currentCompilation.CompilerParameters is CompilerOptions && ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableInternalChecks))
        contract.Requires = this.VisitRequiresList(contract.Requires);
      if (!(this.currentCompilation != null && this.currentCompilation.CompilerParameters is CompilerOptions && ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableInternalChecks))
        contract.Ensures = this.VisitEnsuresList(contract.Ensures);
      // don't visit the Modifies clause since no code is generated for it
      //      contract.Modifies = this.VisitExpressionList(contract.Modifies);
      //      contract = base.VisitMethodContract(contract); don't let base visit it!

      contract.Requires = copy.Requires;
      contract.Ensures = copy.Ensures;

      return contract;

    }
Example #38
0
        protected static void CreateDuplicator()
        {
            _duplicator = new Duplicator(SourceDirectory, TargetDirectory, new TestConfiguration());

            Wait.Until(() => _duplicator.IsAlive);
        }