Exemple #1
0
 protected override IExpression DoConvertExpression(IExpression expr)
 {
     if (lhs != null)
     {
         // expr must be a sub-expression of lhs
         Containers  containers = new Containers(context);
         Containers  exprContainers;
         IExpression newExpr = analysis.GetNewExpression(expr, containers, out exprContainers);
         if (newExpr != null)
         {
             // replace the assignment
             //   expr[indices] = rhs;
             // with
             //   newExpr[indices] = rhs;
             //   expr[indices] = newExpr[indices];
             IExpression replacedLhs = Builder.ReplaceExpression(lhs, expr, newExpr);
             IExpression ae          = Builder.AssignExpr(lhs, replacedLhs);
             IStatement  st          = Builder.ExprStatement(ae);
             containers = Containers.RemoveUnusedLoops(containers, context, lhs);
             int        ancIndex = containers.GetMatchingAncestorIndex(context);
             Containers missing  = containers.GetContainersNotInContext(context, ancIndex);
             st = Containers.WrapWithContainers(st, missing.inputs);
             context.AddStatementAfterAncestorIndex(ancIndex, st);
             // attach the original rhs as an attribute on the new assignment
             IAssignExpression iae = context.FindAncestor <IAssignExpression>();
             MarginalPrototype mp  = new MarginalPrototype(null);
             mp.prototypeExpression = iae.Expression;
             context.OutputAttributes.Set(ae, mp);
             return(newExpr);
         }
     }
     return(base.DoConvertExpression(expr));
 }
Exemple #2
0
        /// <summary>
        /// Remove assignments to variables which are copies of other variables.
        /// </summary>
        /// <param name="iae"></param>
        /// <returns></returns>
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            IExpression copyExpr = GetCopyExpr(iae.Target);

            if (iae.Target is IVariableDeclarationExpression ivde)
            {
                ConvertExpression(ivde);
            }
            if (iae.Expression.Equals(copyExpr))
            {
                return(iae); // was 'null'
            }
            // convert only right hand side
            IExpression expr = ConvertExpression(iae.Expression);

            if (ReferenceEquals(expr, iae.Expression))
            {
                return(iae);
            }
            IAssignExpression ae = Builder.AssignExpr();

            ae.Expression = expr;
            ae.Target     = iae.Target;
            context.InputAttributes.CopyObjectAttributesTo(iae, context.OutputAttributes, ae);
            return(ae);
        }
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            // for(i) array[i] = rhs
            // becomes:
            // temp = CopyStorage(array)
            // for(i) temp[i] = rhs
            // for(i) array[i] = SetTo(temp[i])
            IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(iae.Target);
            string name = VariableInformation.GenerateName(context, ivd.Name + "_new");
            IVariableDeclaration clone = Builder.VarDecl(name, ivd.VariableType);
            var         cloneDeclExpr  = Builder.VarDeclExpr(clone);
            var         newTarget      = Builder.ReplaceExpression(iae.Target, Builder.VarRefExpr(ivd), Builder.VarRefExpr(clone));
            IExpression copyStorage    = Builder.StaticGenericMethod(
                new Func <PlaceHolder, PlaceHolder>(ArrayHelper.CopyStorage),
                new[] { ivd.VariableType }, Builder.VarRefExpr(ivd));
            var cloneDeclStmt = Builder.AssignStmt(cloneDeclExpr, copyStorage);

            context.OutputAttributes.Set(cloneDeclStmt, new Initializer());
            cloneDecls.Add(cloneDeclStmt);
            IExpression setTo = Builder.StaticGenericMethod(
                new Func <PlaceHolder, PlaceHolder, PlaceHolder>(ArrayHelper.SetTo),
                new[] { iae.GetExpressionType() }, iae.Target, newTarget);
            IStatement setToStmt = Builder.AssignStmt(iae.Target, setTo);

            setToStmt = Containers.WrapWithContainers(setToStmt, containers);
            cloneUpdates.Add(setToStmt);
            return(Builder.AssignExpr(newTarget, iae.Expression));
        }
        private static bool IsNullDeclaration(IStatement state)
        {
            IExpressionStatement state_exp = state as IExpressionStatement;

            if (state_exp == null)
            {
                return(false);
            }

            IVariableDeclarationExpression exp_var;

            IAssignExpression exp_assign = state_exp.Expression as IAssignExpression;

            if (exp_assign != null)
            {
                // T value=nullptr; の場合
                ILiteralExpression exp_lit = exp_assign.Expression as ILiteralExpression;
                if (exp_lit == null || exp_lit.Value != null)
                {
                    return(false);
                }
                exp_var = exp_assign.Target as IVariableDeclarationExpression;
            }
            else
            {
                // T value; の場合
                exp_var = state_exp.Expression as IVariableDeclarationExpression;
            }

            return(exp_var != null);
        }
 protected override IExpression ConvertAssign(IAssignExpression iae)
 {
     if (iterationVar != null)
     {
         bool isOperatorStmt = false;
         foreach (var ist in context.FindAncestors <IStatement>())
         {
             if (context.InputAttributes.Has <OperatorStatement>(ist))
             {
                 isOperatorStmt = true;
                 break;
             }
         }
         if (isOperatorStmt)
         {
             // do not trace assignments to loop variables
             var  target    = Recognizer.GetTarget(iae.Target);
             var  ivd       = Recognizer.GetVariableDeclaration(target);
             bool isLoopVar = (ivd != null && Recognizer.GetLoopForVariable(context, ivd) != null);
             if (!isLoopVar)
             {
                 RegisterVariable(target);
             }
         }
     }
     return(base.ConvertAssign(iae));
 }
Exemple #6
0
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            IExpression oldLhs = lhs;

            lhs = null;
            IExpression expr = ConvertExpression(iae.Expression);

            // do not replace the lhs if this is just an array create statement
            if (!(expr is IArrayCreateExpression))
            {
                lhs = iae.Target;
            }
            IExpression target = ConvertExpression(iae.Target);

            lhs = oldLhs;
            if (ReferenceEquals(expr, iae.Expression) && ReferenceEquals(target, iae.Target))
            {
                return(iae);
            }
            IAssignExpression ae = Builder.AssignExpr();

            ae.Expression = expr;
            ae.Target     = target;
            context.InputAttributes.CopyObjectAttributesTo(iae, context.OutputAttributes, ae);
            return(ae);
        }
Exemple #7
0
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            IExpression targ = Recognizer.StripIndexers(iae.Target);

            if (targ is IArgumentReferenceExpression)
            {
                IArgumentReferenceExpression iare = (IArgumentReferenceExpression)targ;
                if (!(iae.Expression is IMethodInvokeExpression))
                {
                    Error("Cannot redefine the value of parameter '" + iare.Parameter.Name + "'.");
                }
            }
            IAssignExpression ae;

            if (iae.Expression is IArrayCreateExpression)
            {
                // We need to process the target first, rather than last, as normal
                ae            = Builder.AssignExpr();
                ae.Target     = ConvertExpression(iae.Target);
                ae.Expression = ConvertExpression(iae.Expression);
                context.InputAttributes.CopyObjectAttributesTo(iae, context.OutputAttributes, ae);
            }
            else
            {
                ae = (IAssignExpression)base.ConvertAssign(iae);
            }
            if (ae.Target == null)
            {
                return(null);
            }
            return(ae);
        }
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            object     targetDecl = Recognizer.GetArrayDeclaration(iae.Target);
            IStatement increment;

            if (this.isOperatorStatement && targetDecl is IVariableDeclaration)
            {
                IVariableDeclaration ivd = (IVariableDeclaration)targetDecl;
                if (analysis.onUpdate.TryGetValue(targetDecl, out increment))
                {
                    IExpression incrExpr   = ((IExpressionStatement)increment).Expression;
                    Containers  containers = new Containers(context);
                    containers.AddContainersNeededForExpression(context, incrExpr);
                    containers = Containers.RemoveUnusedLoops(containers, context, incrExpr);
                    containers = Containers.RemoveStochasticConditionals(containers, context);
                    List <Containers> list;
                    if (!containersOfUpdate.TryGetValue(targetDecl, out list))
                    {
                        list = new List <Containers>();
                        containersOfUpdate[targetDecl] = list;
                    }
                    // have we already performed this update in these containers?
                    bool alreadyDone = false;
                    foreach (Containers prevContainers in list)
                    {
                        if (containers.Contains(prevContainers))
                        {
                            // prevContainers is more general, i.e. has fewer containers than 'containers'
                            alreadyDone = true;
                            break;
                        }
                    }
                    if (!alreadyDone)
                    {
                        list.Add(containers);
                        // must set this attribute before the statement is wrapped
                        context.OutputAttributes.Set(increment, new OperatorStatement());
                        int        ancIndex = containers.GetMatchingAncestorIndex(context);
                        Containers missing  = containers.GetContainersNotInContext(context, ancIndex);
                        increment = Containers.WrapWithContainers(increment, missing.outputs);
                        context.AddStatementAfterAncestorIndex(ancIndex, increment);
                    }
                }
                if (analysis.suppressUpdate.ContainsKey(ivd))
                {
                    foreach (IStatement ist in context.FindAncestors <IStatement>())
                    {
                        if (context.InputAttributes.Has <OperatorStatement>(ist))
                        {
                            var attr = analysis.suppressUpdate[ivd];
                            context.OutputAttributes.Set(ist, new HasIncrement(attr));
                            break;
                        }
                    }
                }
            }
            return(base.ConvertAssign(iae));
        }
        protected override IStatement ConvertExpressionStatement(IExpressionStatement ies)
        {
            if (parent == null)
            {
                return(ies);
            }
            bool keepIfStatement = false;
            // Only keep the surrounding if statement when a factor or constraint is being added.
            IExpression expr = ies.Expression;

            if (expr is IMethodInvokeExpression)
            {
                keepIfStatement = true;
                if (CodeRecognizer.IsInfer(expr))
                {
                    keepIfStatement = false;
                }
            }
            else if (expr is IAssignExpression)
            {
                keepIfStatement = false;
                IAssignExpression       iae  = (IAssignExpression)expr;
                IMethodInvokeExpression imie = iae.Expression as IMethodInvokeExpression;
                if (imie != null)
                {
                    keepIfStatement = true;
                    if (imie.Arguments.Count > 0)
                    {
                        // Statements that copy evidence variables should not send evidence messages.
                        IVariableDeclaration ivd    = Recognizer.GetVariableDeclaration(iae.Target);
                        IVariableDeclaration ivdArg = Recognizer.GetVariableDeclaration(imie.Arguments[0]);
                        if (ivd != null && context.InputAttributes.Has <DoNotSendEvidence>(ivd) &&
                            ivdArg != null && context.InputAttributes.Has <DoNotSendEvidence>(ivdArg))
                        {
                            keepIfStatement = false;
                        }
                    }
                }
                else
                {
                    expr = iae.Target;
                }
            }
            if (expr is IVariableDeclarationExpression)
            {
                IVariableDeclarationExpression ivde = (IVariableDeclarationExpression)expr;
                IVariableDeclaration           ivd  = ivde.Variable;
                keepIfStatement = CodeRecognizer.IsStochastic(context, ivd) && !context.InputAttributes.Has <DoNotSendEvidence>(ivd);
            }
            if (!keepIfStatement)
            {
                return(ies);
            }
            IConditionStatement cs = Builder.CondStmt(parent.Condition, Builder.BlockStmt());

            cs.Then.Statements.Add(ies);
            return(cs);
        }
Exemple #10
0
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            // if all args to a deterministic method are non-stoch or ForwardPointMass, the output is ForwardPointMass
            IVariableDeclaration targetVar = Recognizer.GetVariableDeclaration(iae.Target);

            if (targetVar == null || variablesDefinedNonPointMass.Contains(targetVar))
            {
                return(base.ConvertAssign(iae));
            }
            ProcessDefinition(iae.Expression, targetVar, isLhs: true);
            return(base.ConvertAssign(iae));
        }
Exemple #11
0
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            iae = (IAssignExpression)base.ConvertAssign(iae);
            // array allocation should not be treated as defining the variable
            bool shouldDelete = false;

            if (!(iae.Expression is IArrayCreateExpression))
            {
                AddReplicateStatement(iae.Target, iae.Expression, ref shouldDelete);
            }
            return(shouldDelete ? null : iae);
        }
 private void ForEachAttributeOfCodeElementAndContents(object codeElement, Action <ICompilerAttribute> action)
 {
     if ((attributes == null) || (codeElement == null))
     {
         return;
     }
     foreach (var attr in attributes.GetAll <ICompilerAttribute>(codeElement))
     {
         action(attr);
     }
     if (codeElement is IStatement)
     {
         if (codeElement is IExpressionStatement)
         {
             IExpressionStatement ies = (IExpressionStatement)codeElement;
             ForEachAttributeOfCodeElement(ies.Expression, action);
             if (ies.Expression is IVariableDeclarationExpression)
             {
                 ForEachAttributeOfCodeElement(((IVariableDeclarationExpression)ies.Expression).Variable, action);
             }
             else if (ies.Expression is IAssignExpression)
             {
                 IAssignExpression iae = (IAssignExpression)ies.Expression;
                 if (iae.Target is IVariableDeclarationExpression)
                 {
                     ForEachAttributeOfCodeElement(((IVariableDeclarationExpression)iae.Target).Variable, action);
                 }
                 if (iae.Expression is IMethodInvokeExpression)
                 {
                     ForEachAttributeOfCodeElement(iae.Expression, action);
                 }
             }
         }
         else if (codeElement is IForStatement)
         {
             IForStatement ifs = (IForStatement)codeElement;
             ForEachAttributeOfCodeElementAndContents(ifs.Initializer, action);
             IBinaryExpression ibe = (IBinaryExpression)ifs.Condition;
             ForEachAttributeOfCodeElementAndContents(ibe.Right, action);
         }
     }
     if (codeElement is IMethodDeclaration)
     {
         IMethodDeclaration imd = (IMethodDeclaration)codeElement;
         foreach (IParameterDeclaration ipd in imd.Parameters)
         {
             ForEachAttributeOfCodeElement(ipd, action);
         }
     }
 }
Exemple #13
0
        /// <summary>
        /// When array creations are assigned to stochastic arrays, this creates corresponding arrays for the marginal and uses channels.
        /// </summary>
        /// <param name="iace"></param>
        /// <returns></returns>
        protected override IExpression ConvertArrayCreate(IArrayCreateExpression iace)
        {
            IAssignExpression iae = context.FindAncestor <IAssignExpression>();

            if (iae == null)
            {
                return(iace);
            }
            if (iae.Expression != iace)
            {
                return(iace);
            }
            IVariableDeclaration         ivd  = Recognizer.GetVariableDeclaration(iae.Target);
            VariableToChannelInformation vtci = context.InputAttributes.Get <VariableToChannelInformation>(ivd);

            if (vtci == null)
            {
                return(iace);              // not a stochastic variable
            }
            // Check if this is the last level of indexing
            bool lastLevel = (!(iace.Type is IArrayType));

            if ((lastLevel) && (vtci.usesEqualDefsStatements != null))
            {
                if (vtci.IsUsesEqualDefsStatementInserted)
                {
                    //Error("Duplicate array allocation.");
                }
                else
                {
                    // Insert the UsesEqualDef statement after the array is fully allocated.
                    // Note the array elements will not have been defined yet.
                    LoopContext    lc  = context.InputAttributes.Get <LoopContext>(ivd);
                    RefLoopContext rlc = lc.GetReferenceLoopContext(context);
                    // IMPORTANT TODO: add this statement at the right level!
                    IStatement ist = context.FindAncestor <IStatement>();
                    if (rlc.loops.Count > 0)
                    {
                        ist = rlc.loops[0];
                    }
                    int        ancIndex         = context.GetAncestorIndex(ist);
                    Containers containers       = context.InputAttributes.Get <Containers>(ivd);
                    Containers containersNeeded = containers.GetContainersNotInContext(context, ancIndex);
                    vtci.usesEqualDefsStatements = Containers.WrapWithContainers(vtci.usesEqualDefsStatements, containersNeeded.outputs);
                    context.AddStatementsAfter(ist, vtci.usesEqualDefsStatements);
                    vtci.IsUsesEqualDefsStatementInserted = true;
                }
            }
            return(iace);
        }
        /// <summary>
        /// Convert random assignments to derived variables
        /// </summary>
        /// <param name="iae"></param>
        /// <returns></returns>
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            iae = (IAssignExpression)base.ConvertAssign(iae);
            IStatement ist = context.FindAncestor <IStatement>();

            if (!context.InputAttributes.Has <Models.Constraint>(ist) &&
                (iae.Expression is IMethodInvokeExpression))
            {
                IMethodInvokeExpression imie = (IMethodInvokeExpression)iae.Expression;
                IVariableDeclaration    ivd  = Recognizer.GetVariableDeclaration(iae.Target);
                if (ivd != null)
                {
                    bool isDerived = context.InputAttributes.Has <DerivedVariable>(ivd);
                    if (isDerived)
                    {
                        FactorManager.FactorInfo info = CodeRecognizer.GetFactorInfo(context, imie);
                        if (!info.IsDeterministicFactor)
                        {
                            // The variable is derived, but this definition is not derived.
                            // Thus we must convert
                            //   y = sample()
                            // into
                            //   y_random = sample()
                            //   y = Copy(y_random)
                            // where y_random is not derived.
                            VariableInformation varInfo = VariableInformation.GetVariableInformation(context, ivd);
                            IList <IStatement>  stmts   = Builder.StmtCollection();
                            string name = ivd.Name + "_random" + (Count++);
                            List <IList <IExpression> > indices  = Recognizer.GetIndices(iae.Target);
                            IVariableDeclaration        cloneVar = varInfo.DeriveIndexedVariable(stmts, context, name, indices, copyInitializer: true);
                            context.OutputAttributes.Remove <DerivedVariable>(cloneVar);
                            stmts.Add(Builder.AssignStmt(Builder.VarRefExpr(cloneVar), iae.Expression));
                            int ancIndex = context.FindAncestorIndex <IStatement>();
                            context.AddStatementsBeforeAncestorIndex(ancIndex, stmts);
                            Type tp = iae.Target.GetExpressionType();
                            if (tp == null)
                            {
                                Error("Could not determine type of expression: " + iae.Target);
                                return(iae);
                            }
                            IExpression copy = Builder.StaticGenericMethod(new Func <PlaceHolder, PlaceHolder>(Clone.Copy), new Type[] { tp },
                                                                           Builder.VarRefExpr(cloneVar));
                            iae = Builder.AssignExpr(iae.Target, copy);
                        }
                    }
                }
            }
            return(iae);
        }
Exemple #15
0
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            var oldTargets = targetsOfCurrentAssignment;

            targetsOfCurrentAssignment = new Set <IExpression>(ReferenceEqualityComparer <IExpression> .Instance);
            iae = (IAssignExpression)base.ConvertAssign(iae);
            targetsOfCurrentAssignment.Add(iae.Target);
            IExpression rhs          = iae.Expression;
            bool        shouldDelete = false;

            foreach (IExpression target in targetsOfCurrentAssignment)
            {
                ProcessAssign(target, rhs, ref shouldDelete);
            }
            targetsOfCurrentAssignment = oldTargets;
            return(shouldDelete ? null : iae);
        }
Exemple #16
0
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            // set index variables on the converted target, using the unconverted lhs indices
            // this code is copied from ModelAnalysisTransform
            IAssignExpression     ae  = (IAssignExpression)base.ConvertAssign(iae);
            IParameterDeclaration ipd = null;
            IVariableDeclaration  ivd = Recognizer.GetVariableDeclaration(ae.Target);

            if (ivd == null)
            {
                ipd = Recognizer.GetParameterDeclaration(ae.Target);
                if (ipd == null)
                {
                    return(ae);
                }
            }
            if (iae.Target is IArrayIndexerExpression)
            {
                // Gather index variables from the left-hand side of the assignment
                object decl            = (ipd == null) ? (object)ivd : ipd;
                VariableInformation vi = VariableInformation.GetVariableInformation(context, decl);
                try
                {
                    List <IVariableDeclaration[]> indVars = new List <IVariableDeclaration[]>();
                    Recognizer.AddIndexers(context, indVars, iae.Target);
                    // Sets the size of this variable at this array depth
                    int depth = Recognizer.GetIndexingDepth(iae.Target);
                    // if this statement is actually a constraint, then we don't need to enforce matching of index variables
                    bool isConstraint = context.InputAttributes.Has <Models.Constraint>(context.FindAncestor <IStatement>());
                    for (int i = 0; i < depth; i++)
                    {
                        vi.SetIndexVariablesAtDepth(i, indVars[i], allowMismatch: isConstraint);
                    }
                }
                catch (Exception ex)
                {
                    Error(ex.Message, ex);
                }
                if (!context.InputAttributes.Has <VariableInformation>(decl))
                {
                    context.InputAttributes.Set(decl, vi);
                }
            }
            return(ae);
        }
Exemple #17
0
        public override bool Equals(object obj)
        {
            if (this == obj)
            {
                return(true);
            }

            IAssignExpression expression = obj as IAssignExpression;

            if (expression == null)
            {
                return(false);
            }

            return
                (this.Expression.Equals(expression.Expression) &&
                 this.Target.Equals(expression.Target));
        }
Exemple #18
0
        internal static ConditionBinding GetInitializerBinding(IForStatement ifs)
        {
            IStatement ist = ifs.Initializer;

            if (ist is IBlockStatement)
            {
                if (((IBlockStatement)ist).Statements.Count != 1)
                {
                    throw new Exception("Unhandled loop initializer: " + ist);
                }
                ist = ((IBlockStatement)ist).Statements[0];
            }
            IExpressionStatement init = (IExpressionStatement)ist;
            IAssignExpression    iae  = (IAssignExpression)init.Expression;
            IVariableDeclaration ivd  = Recognizer.GetVariableDeclaration(iae.Target);

            return(new ConditionBinding(Builder.VarRefExpr(ivd), iae.Expression));
        }
Exemple #19
0
        //CodeTransformer ct = new CodeTransformer();
        protected Node AddNode(GraphWriter g, IStatement ist, Stage stage)
        {
            if (ist is ICommentStatement)
            {
                return(null);
            }
            Node nd = GetNodeForStatement(ist, stage);

            if (nd != null)
            {
                nd.Label = Count + "," + nd.Label;
                Count++;
                return(nd);
            }
            DependencyInformation di = context.InputAttributes.Get <DependencyInformation>(ist);

            if ((di != null) && (di.IsOutput))
            {
                return(null);
            }
            string s = Count + ". " + StatementLabel(ist);

            nd          = g.AddNode("node" + Count);
            nd.UserData = Count++;
            SetNodeForStatement(ist, stage, nd);
            //if (di.IsOutput) nd.Fillcolor = Color.LightBlue;
            nd.Label = s;
            if (stage == Stage.Initialisation)
            {
                nd.FillColor = Color.LightGray;
            }
            if (ist is IExpressionStatement)
            {
                IExpressionStatement ies = (IExpressionStatement)ist;
                IAssignExpression    iae = ies.Expression as IAssignExpression;
                if ((iae != null) && (iae.Target is IVariableDeclarationExpression))
                {
                    nd.BorderWidth = 2;
                }
            }
            nd.Shape    = ShapeStyle.Box;
            nd.FontSize = 9;
            return(nd);
        }
 protected override IExpression ConvertAssign(IAssignExpression iae)
 {
     iae = (IAssignExpression)base.ConvertAssign(iae);
     if (iae.Target is IArrayIndexerExpression target && iae.Expression is IObjectCreateExpression ioce)
     {
         IExpression parent = target.Target;
         Type        type   = Builder.ToType(ioce.Type);
         if (MessageTransform.IsFileArray(type) && MessageTransform.IsFileArray(parent.GetExpressionType()) && ioce.Arguments.Count == 2)
         {
             // change new FileArray(name, dimensions) into FileArray(parent, index, dimensions)
             IList <IExpression> args = Builder.ExprCollection();
             args.Add(target.Target);
             args.AddRange(target.Indices);
             args.Add(ioce.Arguments[1]);
             return(Builder.AssignExpr(target, Builder.NewObject(type, args)));
         }
     }
     return(iae);
 }
Exemple #21
0
 protected override IExpression ConvertAssign(IAssignExpression iae)
 {
     if (loggingAction != null)
     {
         if (iae.Expression is IArrayCreateExpression || iae.Expression is IObjectCreateExpression)
         {
             string name = iae.Target.ToString();
             if (!name.Contains("_local") && !(iae.Target is IArrayIndexerExpression))
             {
                 var message = Builder.LiteralExpr("Allocating " + name);
                 var invoke  = Builder.DelegateInvokeExpr();
                 invoke.Target = loggingAction;
                 invoke.Arguments.Add(message);
                 context.AddStatementAfterCurrent(Builder.ExprStatement(invoke));
             }
         }
     }
     return(base.ConvertAssign(iae));
 }
Exemple #22
0
        private NodeInfo GetNodeInfo(IExpression factor)
        {
            IExpression             target = null;
            IMethodInvokeExpression imie;

            if (factor is IAssignExpression)
            {
                IAssignExpression iae = (IAssignExpression)factor;
                target = iae.Target;
                if (target is IVariableDeclarationExpression)
                {
                    IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(target);
                    target = Builder.VarRefExpr(ivd);
                }
                imie = (IMethodInvokeExpression)iae.Expression;
            }
            else
            {
                imie = (IMethodInvokeExpression)factor;
            }
            NodeInfo info = new NodeInfo(imie);

            info.info = CodeRecognizer.GetFactorInfo(context, imie);
            if (target != null)
            {
                info.isReturnOrOut.Add(true);
                info.arguments.Add(target);
            }
            if (!info.info.Method.IsStatic)
            {
                info.isReturnOrOut.Add(false);
                info.arguments.Add(imie.Method.Target);
            }
            foreach (IExpression arg in imie.Arguments)
            {
                bool isOut = (arg is IAddressOutExpression);
                info.isReturnOrOut.Add(isOut);
                info.arguments.Add(isOut ? ((IAddressOutExpression)arg).Expression : arg);
            }
            return(info);
        }
Exemple #23
0
 protected override IStatement ConvertExpressionStatement(IExpressionStatement ies)
 {
     if (ies.Expression is IAssignExpression)
     {
         IAssignExpression iae = (IAssignExpression)ies.Expression;
         if (iae.Expression is IMethodInvokeExpression)
         {
             factorExprs.Add(ies.Expression);
         }
     }
     else if (ies.Expression is IMethodInvokeExpression)
     {
         IMethodInvokeExpression imie = (IMethodInvokeExpression)ies.Expression;
         if (CodeRecognizer.IsInfer(imie))
         {
             return(ies);
         }
         factorExprs.Add(ies.Expression);
     }
     return(ies);
 }
 /// <summary>
 /// Attach DerivedVariable attributes to newly created variables
 /// </summary>
 /// <param name="iae"></param>
 /// <returns></returns>
 protected override IExpression ConvertAssign(IAssignExpression iae)
 {
     iae = (IAssignExpression)base.ConvertAssign(iae);
     if (iae.Expression is IMethodInvokeExpression imie)
     {
         IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(iae.Target);
         if (ivd != null)
         {
             bool isDerived = context.InputAttributes.Has <DerivedVariable>(ivd);
             if (!isDerived)
             {
                 FactorManager.FactorInfo info = CodeRecognizer.GetFactorInfo(context, imie);
                 if (info.IsDeterministicFactor)
                 {
                     context.InputAttributes.Set(ivd, new DerivedVariable());
                 }
             }
         }
     }
     return(iae);
 }
        //===========================================================
        //		構文合致: function-try-statement
        //		判定が難しい為之は延期
        //		・catch 等から抜ける全てのパスで throw しているか確認しなければならない
        //===========================================================
        public static bool IsFunctionTry(IStatementCollection states)
        {
            if (states == null || states.Count == 0)
            {
                return(false);
            }

            // 前に連なっても OK なのは T var=nullptr のみ (この場合には最初の使用時に T も一緒に表示させなければならない...)
            int last = states.Count - 1;

            for (int i = 0; i < last; i++)
            {
                IExpressionStatement state_exp = states[i] as IExpressionStatement;
                if (state_exp == null)
                {
                    return(false);
                }

                IAssignExpression exp_assign = state_exp.Expression as IAssignExpression;
                if (exp_assign == null)
                {
                    return(false);
                }

                IVariableDeclaration decl = exp_assign.Target as IVariableDeclaration;
                if (decl == null)
                {
                    return(false);
                }

                ILiteralExpression exp_lit = exp_assign.Expression as ILiteralExpression;
                if (exp_lit == null || exp_lit.Value != null)
                {
                    return(false);
                }
            }

            return(false);
        }
        //===========================================================
        //		細かい関数
        //===========================================================
        private static void RemoveNullDeclaration(string name, Gen::List <IStatement> yields)
        {
            for (int i = 0, iM = yields.Count; i < iM; i++)
            {
                IExpressionStatement state_exp = yields[i] as IExpressionStatement;
                if (state_exp == null)
                {
                    continue;
                }

                IVariableDeclarationExpression exp_var;

                IAssignExpression exp_assign = state_exp.Expression as IAssignExpression;
                if (exp_assign != null)
                {
                    // T value=nullptr; の場合
                    ILiteralExpression exp_lit = exp_assign.Expression as ILiteralExpression;
                    if (exp_lit == null || exp_lit.Value != null)
                    {
                        continue;
                    }
                    exp_var = exp_assign.Target as IVariableDeclarationExpression;
                }
                else
                {
                    // T value; の場合
                    exp_var = state_exp.Expression as IVariableDeclarationExpression;
                }

                if (exp_var == null || exp_var.Variable.Name != name)
                {
                    continue;
                }

                yields.RemoveAt(i);
                break;
            }
        }
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            IParameterDeclaration ipd = null;
            IVariableDeclaration  ivd = Recognizer.GetVariableDeclaration(iae.Target);

            if (ivd == null)
            {
                ipd = Recognizer.GetParameterDeclaration(iae.Target);
                if (ipd == null)
                {
                    return(base.ConvertAssign(iae));
                }
            }
            IAssignExpression ae = (IAssignExpression)base.ConvertAssign(iae);

            if (ipd == null && !context.InputAttributes.Has <IsInferred>(ivd))
            {
                // assignment to a local variable
                if (ae.Expression is ILiteralExpression)
                {
                    bool isLoopInitializer = (Recognizer.GetAncestorIndexOfLoopBeingInitialized(context) != -1);
                    if (!isLoopInitializer)
                    {
                        Type valueType = ae.Expression.GetExpressionType();
                        if (Quoter.ShouldInlineType(valueType))
                        {
                            // inline all future occurrences of this variable with the rhs expression
                            conditionContext.Add(new ConditionBinding(ae.Target, ae.Expression));
                        }
                    }
                }
            }
            else
            {
                // assignment to a method parameter
            }
            return(ae);
        }
Exemple #28
0
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            int index = assignmentIndex;

            assignmentIndex++;
            var ae = (IAssignExpression)base.ConvertAssign(iae);

            if (ae != null)
            {
                var lhsLiveness = liveness[index];
                if (lhsLiveness == LivenessAnalysisTransform.Liveness.Unused)
                {
                    return(null);
                }
                else if (lhsLiveness == LivenessAnalysisTransform.Liveness.Dead)
                {
                    //Trace.WriteLine($"dead assign: {iae}");
                    if (ae.Target is IVariableDeclarationExpression)
                    {
                        if (ae.Expression is IDefaultExpression)
                        {
                            return(ae);
                        }
                        else
                        {
                            return(Builder.AssignExpr(ae.Target, Builder.DefaultExpr(ae.Target.GetExpressionType())));
                        }
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            return(ae);
        }
        /// <summary>
        /// Assignments to non-stochastic non-loop integer variables are added to the conditionContext
        /// </summary>
        /// <param name="iae"></param>
        /// <returns></returns>
        protected override IExpression ConvertAssign(IAssignExpression iae)
        {
            IExpression          expr   = ConvertExpression(iae.Expression);
            IExpression          target = ConvertExpression(iae.Target);
            IVariableDeclaration ivd    = Recognizer.GetVariableDeclaration(target);

            if (ivd != null)
            {
                var varInfo = VariableInformation.GetVariableInformation(context, ivd);
                if (!varInfo.IsStochastic && varInfo.varType.Equals(typeof(int)) && Recognizer.GetLoopForVariable(context, ivd) == null)
                {
                    // add the assignment as a binding
                    if (target is IVariableDeclarationExpression ivde)
                    {
                        target = Builder.VarRefExpr(ivde.Variable);
                    }
                    ConditionBinding binding = new ConditionBinding(target, expr);
                    conditionContext.Add(binding);
                    // when current lexical scope ends, remove this binding?
                    // no, because locals aren't correctly scoped yet
                }
            }
            return(iae);
        }
 public virtual IExpression TransformAssignExpression(IAssignExpression value)
 {
     value.Target = this.TransformExpression(value.Target);
     value.Expression = this.TransformExpression(value.Expression);
     return value;
 }
Exemple #31
0
 protected override IExpression ConvertAssign(IAssignExpression iae)
 {
     foreach (IStatement stmt in context.FindAncestors <IStatement>())
     {
         // an initializer statement may perform a copy, but it is not valid to replace the lhs
         // in that case.
         if (context.InputAttributes.Has <Initializer>(stmt))
         {
             return(iae);
         }
     }
     // Look for assignments where the right hand side is a SetTo call
     if (iae.Expression is IMethodInvokeExpression imie)
     {
         bool isCopy                          = Recognizer.IsStaticGenericMethod(imie, new Func <PlaceHolder, PlaceHolder>(Clone.Copy));
         bool isSetTo                         = Recognizer.IsStaticGenericMethod(imie, typeof(ArrayHelper), "SetTo");
         bool isSetAllElementsTo              = Recognizer.IsStaticGenericMethod(imie, typeof(ArrayHelper), "SetAllElementsTo");
         bool isGetItemsPoint                 = Recognizer.IsStaticGenericMethod(imie, typeof(GetItemsPointOp <>), "ItemsAverageConditional");
         bool isGetJaggedItemsPoint           = Recognizer.IsStaticGenericMethod(imie, typeof(GetJaggedItemsPointOp <>), "ItemsAverageConditional");
         bool isGetDeepJaggedItemsPoint       = Recognizer.IsStaticGenericMethod(imie, typeof(GetDeepJaggedItemsPointOp <>), "ItemsAverageConditional");
         bool isGetItemsFromJaggedPoint       = Recognizer.IsStaticGenericMethod(imie, typeof(GetItemsFromJaggedPointOp <>), "ItemsAverageConditional");
         bool isGetItemsFromDeepJaggedPoint   = Recognizer.IsStaticGenericMethod(imie, typeof(GetItemsFromDeepJaggedPointOp <>), "ItemsAverageConditional");
         bool isGetJaggedItemsFromJaggedPoint = Recognizer.IsStaticGenericMethod(imie, typeof(GetJaggedItemsFromJaggedPointOp <>), "ItemsAverageConditional");
         if (isCopy || isSetTo || isSetAllElementsTo || isGetItemsPoint ||
             isGetJaggedItemsPoint || isGetDeepJaggedItemsPoint || isGetJaggedItemsFromJaggedPoint ||
             isGetItemsFromJaggedPoint || isGetItemsFromDeepJaggedPoint)
         {
             IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(iae.Target);
             // Find the condition context
             var ifs         = context.FindAncestors <IConditionStatement>();
             var condContext = new List <IConditionStatement>();
             foreach (var ifSt in ifs)
             {
                 if (!CodeRecognizer.IsStochastic(context, ifSt.Condition))
                 {
                     condContext.Add(ifSt);
                 }
             }
             var         copyAttr = context.InputAttributes.GetOrCreate <CopyOfAttribute>(ivd, () => new CopyOfAttribute());
             IExpression rhs;
             if (isSetTo || isSetAllElementsTo)
             {
                 // Mark as copy of the second argument
                 rhs = imie.Arguments[1];
             }
             else
             {
                 // Mark as copy of the first argument
                 rhs = imie.Arguments[0];
             }
             InitialiseTo init = context.InputAttributes.Get <InitialiseTo>(ivd);
             if (init != null)
             {
                 IVariableDeclaration ivdRhs  = Recognizer.GetVariableDeclaration(rhs);
                 InitialiseTo         initRhs = (ivdRhs == null) ? null : context.InputAttributes.Get <InitialiseTo>(ivdRhs);
                 if (initRhs == null || !initRhs.initialMessagesExpression.Equals(init.initialMessagesExpression))
                 {
                     // Do not replace a variable with a unique initialiser
                     return(iae);
                 }
             }
             var initBack = context.InputAttributes.Get <InitialiseBackwardTo>(ivd);
             if (initBack != null && !(initBack.initialMessagesExpression is IArrayCreateExpression))
             {
                 IVariableDeclaration ivdRhs  = Recognizer.GetVariableDeclaration(rhs);
                 InitialiseBackwardTo initRhs = (ivdRhs == null) ? null : context.InputAttributes.Get <InitialiseBackwardTo>(ivdRhs);
                 if (initRhs == null || !initRhs.initialMessagesExpression.Equals(init.initialMessagesExpression))
                 {
                     // Do not replace a variable with a unique initialiser
                     return(iae);
                 }
             }
             if (isCopy || isSetTo)
             {
                 RemoveMatchingSuffixes(iae.Target, rhs, condContext, out IExpression lhsPrefix, out IExpression rhsPrefix);
                 copyAttr.copyMap[lhsPrefix] = new CopyOfAttribute.CopyContext {
                     Expression = rhsPrefix, ConditionContext = condContext
                 };
             }
             else if (isSetAllElementsTo)
             {
                 copyAttr.copiedInEveryElementMap[iae.Target] = new CopyOfAttribute.CopyContext {
                     Expression = rhs, ConditionContext = condContext
                 };
             }
             else if (isGetItemsPoint || isGetJaggedItemsPoint || isGetDeepJaggedItemsPoint || isGetItemsFromJaggedPoint || isGetItemsFromDeepJaggedPoint || isGetJaggedItemsFromJaggedPoint)
             {
                 var target     = ((IArrayIndexerExpression)iae.Target).Target;
                 int inputDepth = imie.Arguments.Count - 3;
                 List <IExpression> indexExprs = new List <IExpression>();
                 for (int i = 0; i < inputDepth; i++)
                 {
                     indexExprs.Add(imie.Arguments[1 + i]);
                 }
                 int outputDepth;
                 if (isGetDeepJaggedItemsPoint)
                 {
                     outputDepth = 3;
                 }
                 else if (isGetJaggedItemsPoint || isGetJaggedItemsFromJaggedPoint)
                 {
                     outputDepth = 2;
                 }
                 else
                 {
                     outputDepth = 1;
                 }
                 copyAttr.copyAtIndexMap[target] = new CopyOfAttribute.CopyContext2
                 {
                     Depth             = outputDepth,
                     ConditionContext  = condContext,
                     ExpressionAtIndex = (lhsIndices) =>
                     {
                         return(Builder.JaggedArrayIndex(rhs, indexExprs.ListSelect(indexExpr =>
                                                                                    new[] { Builder.JaggedArrayIndex(indexExpr, lhsIndices) })));
                     }
                 };
             }
             else
             {
                 throw new NotImplementedException();
             }
         }
     }
     return(iae);
 }
            private void WriteAssignExpression(IAssignExpression value, IFormatter formatter)
            {
                IBinaryExpression binaryExpression = value.Expression as IBinaryExpression;
                if (binaryExpression != null)
                {
                    if (value.Target.Equals(binaryExpression.Left))
                    {
                        string operatorText = string.Empty;
                        switch (binaryExpression.Operator)
                        {
                            case BinaryOperator.Add:
                                operatorText = "inc";
                                break;

                            case BinaryOperator.Subtract:
                                operatorText = "dec";
                                break;
                        }

                        if (operatorText.Length != 0)
                        {
                            // Op(a,b)
                            formatter.Write(operatorText);
                            formatter.Write("(");
                            this.WriteExpression(value.Target, formatter);
                            formatter.Write(",");
                            formatter.Write(" ");
                            this.WriteExpression(binaryExpression.Right, formatter);
                            formatter.Write(")");

                            return;
                        }
                    }
                }

                IPropertyReferenceExpression propExpression = value.Target as IPropertyReferenceExpression;
                if (propExpression != null)
                {
                    if (propExpression.Target != null)
                    {
                        this.WriteTargetExpression(propExpression.Target, formatter);
                        formatter.Write(".");
                    }
                    var s = propExpression.Property.Resolve().SetMethod;
                    WriteMethodReference(s, formatter);
                    formatter.Write("(");
                    this.WriteExpression(value.Expression, formatter);
                    formatter.Write(")");
                }
                else
                {
                    // x := y + z
                    this.WriteExpression(value.Target, formatter);
                    formatter.Write(" = ");
                    this.WriteExpression(value.Expression, formatter);
                }
            }
 public virtual void VisitAssignExpression(IAssignExpression value)
 {
     this.VisitExpression(value.Target);
     this.VisitExpression(value.Expression);
 }