Example #1
0
 public static bool IsReducibleArrayCreateExpression(IExpression expr)
 {
     if (expr is IArrayCreateExpression)
     {
         IArrayCreateExpression iace = (IArrayCreateExpression)expr;
         return(iace.Initializer == null);
     }
     else if (expr is IObjectCreateExpression)
     {
         IObjectCreateExpression ioce = (IObjectCreateExpression)expr;
         Type type      = ioce.Type.DotNetType;
         Type gtd       = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
         bool reducible =
             (gtd == typeof(Distributions.DistributionRefArray <,>) &&
              ioce.Arguments.Count == 1) ||
             (gtd == typeof(Distributions.DistributionStructArray <,>) &&
              ioce.Arguments.Count == 1) ||
             (gtd == typeof(Distributions.DistributionRefArray2D <,>) &&
              ioce.Arguments.Count == 2) ||
             (gtd == typeof(Distributions.DistributionStructArray2D <,>) &&
              ioce.Arguments.Count == 2);
         return(reducible && (ioce.Initializer == null));
     }
     else
     {
         return(false);
     }
 }
 public virtual IExpression TransformArrayCreateExpression(IArrayCreateExpression value)
 {
     this.InsituTransformExpressionCollection(value.Dimensions);
     value.Initializer = (IBlockExpression)this.TransformExpression(value.Initializer);
     value.Type = this.TransformType(value.Type);
     return value;
 }
        private static void WriteArrayCreate(LanguageWriter w, IArrayCreateExpression exp)
        {
            w.WriteKeyword("gcnew");
            w.Write(" ");
            w.WriteKeyword("array");
            w.Write("<");

            new TypeRef(exp.Type).WriteNameWithRef(w);
            if (exp.Dimensions != null && exp.Dimensions.Count > 1)
            {
                w.Write(", ");
                w.WriteAsLiteral(exp.Dimensions.Count);
            }
            w.Write(">");

            // 要素数の指定
            if (exp.Dimensions != null)
            {
                w.Write("(");
                w.WriteExpressionCollection(exp.Dimensions);
                w.Write(")");
            }

            // {a, b, ... 要素の指定}
            IBlockExpression initializer = exp.Initializer;

            if (initializer != null)
            {
                WriteBlock(w, initializer);
            }
        }
Example #4
0
        public override bool Equals(object obj)
        {
            if (this == obj)
            {
                return(true);
            }

            IArrayCreateExpression expression = obj as IArrayCreateExpression;

            if (expression == null ||
                (!Type.Equals(expression.Type)) ||
                (Initializer != null && !Initializer.Equals(expression.Initializer)) ||
                Dimensions.Count != expression.Dimensions.Count)
            {
                return(false);
            }

            for (int i = 0; i < Dimensions.Count; i++)
            {
                if (!(Dimensions[i].Equals(expression.Dimensions[i])))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #5
0
        /// <summary>
        /// Gets an expression for the string form of the supplied expression.
        /// </summary>
        /// <param name="expr"></param>
        /// <returns></returns>
        internal static IExpression GetExpressionTextExpression(IExpression expr)
        {
            string msgText = expr.ToString();

            if (msgText.StartsWith("this."))
            {
                msgText = msgText.Substring(5);
            }
            string comma = CSharpWriter.InsertSpaceAfterComma ? ", " : ",";

            if (expr is IArrayIndexerExpression)
            {
                List <IList <IExpression> > indices    = CodeRecognizer.Instance.GetIndices(expr);
                List <IExpression>          indexExprs = new List <IExpression>();
                bool foundVariableIndex = false;
                foreach (IList <IExpression> bracket in indices)
                {
                    StringBuilder bracketSb = new StringBuilder("[");
                    StringBuilder formatSb  = new StringBuilder("[");
                    for (int i = 0; i < bracket.Count; i++)
                    {
                        if (i > 0)
                        {
                            bracketSb.Append(comma);
                            formatSb.Append(",");
                        }
                        IExpression indexExpr = bracket[i];
                        bracketSb.Append(indexExpr);
                        if (indexExpr is ILiteralExpression)
                        {
                            formatSb.Append(indexExpr);
                        }
                        else
                        {
                            foundVariableIndex = true;
                            int formatIndex = indexExprs.Count;
                            formatSb.Append("{");
                            formatSb.Append(formatIndex);
                            formatSb.Append("}");
                            indexExprs.Add(indexExpr);
                        }
                    }
                    bracketSb.Append("]");
                    formatSb.Append("]");
                    msgText = msgText.Replace(bracketSb.ToString(), formatSb.ToString());
                }
                if (foundVariableIndex)
                {
                    IArrayCreateExpression indexArray = Builder.ArrayCreateExpr(typeof(object), Builder.LiteralExpr(indexExprs.Count));
                    indexArray.Initializer = Builder.BlockExpr();
                    indexArray.Initializer.Expressions.AddRange(indexExprs);
                    return(Builder.StaticMethod(new Func <string, object[], string>(string.Format), Builder.LiteralExpr(msgText), indexArray));
                }
            }
            IExpression textExpr = Builder.LiteralExpr(msgText);

            return(textExpr);
        }
Example #6
0
        internal static IExpression MakePlaceHolderArrayCreate(IExpression expr, IList <IVariableDeclaration> indexVars)
        {
            CodeBuilder            Builder = CodeBuilder.Instance;
            IArrayCreateExpression iace    = Builder.ArrayCreateExpr(typeof(PlaceHolder), Util.ArrayInit(indexVars.Count, i => Builder.VarRefExpr(indexVars[i])));

            iace.Initializer = Builder.BlockExpr();
            iace.Initializer.Expressions.Add(expr);
            return(iace);
        }
Example #7
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);
        }
Example #8
0
 public override void VisitArrayCreateExpression(IArrayCreateExpression value)
 {
     if (value.Initializer != null)
     {
         _formatter.Write("$(");
         VisitExpressionCollection(value.Initializer.Expressions, true);
         _formatter.Write(")");
     }
     else
     {
         _formatter.Write("@(");
         VisitExpressionCollection(value.Dimensions, true);
         _formatter.Write(")");
     }
 }
Example #9
0
        // copied from ExpressionEvaluator.cs
        public static IExpression QuoteArray(Array array)
        {
            IArrayCreateExpression ace = Builder.ArrayCreateExpr(array.GetType().GetElementType());

            for (int i = 0; i < array.Rank; i++)
            {
                ace.Dimensions.Add(Builder.LiteralExpr(array.GetLength(i)));
            }
            ace.Initializer = Builder.BlockExpr();
            if (array.Rank == 1)
            {
                foreach (object obj in array)
                {
                    IExpression objExpr = Quote(obj);
                    if (objExpr == null)
                    {
                        return(null);
                    }
                    ace.Initializer.Expressions.Add(objExpr);
                }
                return(ace);
            }
            if (array.Rank == 2)
            {
                for (int i = 0; i < array.GetLength(0); i++)
                {
                    IBlockExpression be = Builder.BlockExpr();
                    ace.Initializer.Expressions.Add(be);
                    for (int j = 0; j < array.GetLength(1); j++)
                    {
                        IExpression objExpr = Quote(array.GetValue(i, j));
                        if (objExpr == null)
                        {
                            return(null);
                        }
                        be.Expressions.Add(objExpr);
                    }
                }
                return(ace);
            }
            return(null);
        }
Example #10
0
        protected override IExpression ConvertArrayCreate(IArrayCreateExpression iace)
        {
            IArrayCreateExpression ace = (IArrayCreateExpression)base.ConvertArrayCreate(iace);
            IAssignExpression      iae = context.FindAncestor <IAssignExpression>();

            if (iae == null)
            {
                return(ace);
            }
            if (iae.Expression != iace)
            {
                return(ace);
            }
            IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(iae.Target);

            if (ivd == null)
            {
                return(ace);
            }
            VariableInformation vi = VariableInformation.GetVariableInformation(context, ivd);
            int depth = Recognizer.GetIndexingDepth(iae.Target);

            IExpression[] dimExprs = new IExpression[ace.Dimensions.Count];
            for (int i = 0; i < dimExprs.Length; i++)
            {
                dimExprs[i] = ace.Dimensions[i];
            }
            bool targetHasLiteralIndices        = false;
            List <IList <IExpression> > indices = Recognizer.GetIndices(iae.Target);

            foreach (IList <IExpression> bracket in indices)
            {
                foreach (IExpression index in bracket)
                {
                    if (index is ILiteralExpression)
                    {
                        targetHasLiteralIndices = true;
                    }
                }
            }

            if (!targetHasLiteralIndices)
            {
                try
                {
                    // Set the size of this array at the lhs indexing depth
                    if (vi.sizes.Count <= depth)
                    {
                        vi.SetSizesAtDepth(depth, dimExprs);
                    }
                }
                catch (Exception ex)
                {
                    Error(ex.Message, ex);
                }
            }
            else
            {
                // input is:  a[0][1] = new int[10];
                // output is: a_size[0][1] = 10;
                if (vi.sizes.Count < depth)
                {
                    throw new Exception("missing size information for " + ivd);
                }
                if (vi.sizes.Count == depth)
                {
                    vi.sizes.Add(new IExpression[dimExprs.Length]);
                }
                vi.DefineIndexVarsUpToDepth(context, depth - 1);
                for (int dim = 0; dim < dimExprs.Length; dim++)
                {
                    IExpression sizeExpr = vi.sizes[depth][dim];
                    if (sizeExpr != null)
                    {
                        continue;
                    }
                    // create a size variable using indexVars and sizes at lower depths
                    List <IExpression[]>          sizes2     = new List <IExpression[]>();
                    List <IVariableDeclaration[]> indexVars2 = new List <IVariableDeclaration[]>();
                    for (int i = 0; i < depth; i++)
                    {
                        sizes2.Add(vi.sizes[i]);
                        if (i < depth - 1)
                        {
                            indexVars2.Add(vi.indexVars[i]);
                        }
                    }
                    Type   tp   = CodeBuilder.MakeJaggedArrayType(typeof(int), sizes2);
                    string name = VariableInformation.GenerateName(context, ivd.Name + "_size");
                    IVariableDeclaration sizeVar = Builder.VarDecl(name, tp);
                    VariableInformation  viSize  = VariableInformation.GetVariableInformation(context, sizeVar);
                    for (int i = 0; i < depth; i++)
                    {
                        viSize.SetSizesAtDepth(i, sizes2[i]);
                        if (i < depth - 1)
                        {
                            viSize.SetIndexVariablesAtDepth(i, indexVars2[i]);
                        }
                    }
                    IList <IStatement> stmts = Builder.StmtCollection();
                    Builder.NewJaggedArray(stmts, sizeVar, indexVars2, sizes2);
                    Containers containers = context.InputAttributes.Get <Containers>(ivd);
                    int        ancIndex   = containers.GetMatchingAncestorIndex(context);
                    context.AddStatementsBeforeAncestorIndex(ancIndex, stmts);
                    sizeExpr             = Builder.JaggedArrayIndex(Builder.VarRefExpr(sizeVar), vi.GetIndexExpressions(context, depth));
                    vi.sizes[depth][dim] = sizeExpr;
                    var assignStmt = Builder.AssignStmt(Builder.JaggedArrayIndex(Builder.VarRefExpr(sizeVar), indices), dimExprs[dim]);
                    context.AddStatementAfterCurrent(assignStmt);
                }
            }
            if (iace.Initializer != null)
            {
                // array is being filled in by an initializer, rather than loops.
                // need to fill in the remaining sizes
                vi.DefineSizesUpToDepth(context, vi.ArrayDepth);
            }
            return(ace);
        }
Example #11
0
 public CArrayType(IArrayCreateExpression exp)
     : this(exp.Type, new CDimensionCollection(exp.Dimensions))
 {
 }
Example #12
0
            //===========================================================
            //		Expression 分岐
            //===========================================================
            public virtual void WriteExpression(IExpression expression)
            {
                if (expression == null)
                {
                    return;
                }

                mwg.Reflector.CppCli.ExpressionWriter.WriteExpression(this, expression, false);

#if FALSE
#pragma warning disable 612

                IMemberInitializerExpression expression3 = expression as IMemberInitializerExpression;
                if (expression3 != null)
                {
                    this.WriteMemberInitializerExpression(expression3);
                    return;
                }

                IAddressOutExpression expression27 = expression as IAddressOutExpression;
                if (expression27 != null)
                {
                    this.WriteAddressOutExpression(expression27);
                    return;
                }

                IAddressReferenceExpression expression26 = expression as IAddressReferenceExpression;
                if (expression26 != null)
                {
                    this.WriteAddressReferenceExpression(expression26);
                    return;
                }

                IDelegateCreateExpression iDelegateCreateExpression = expression as IDelegateCreateExpression;
                if (iDelegateCreateExpression != null)
                {
                    this.WriteDelegateCreateExpression(iDelegateCreateExpression);
                    return;
                }

                IMethodInvokeExpression iMethodInvokeExpression = expression as IMethodInvokeExpression;
                if (iMethodInvokeExpression != null)
                {
                    this.WriteMethodInvokeExpression(iMethodInvokeExpression);
                    return;
                }

                IVariableDeclarationExpression expression15 = expression as IVariableDeclarationExpression;
                if (expression15 != null)
                {
                    this.WriteVariableDeclaration(expression15.Variable);
                    return;
                }

                ITypeOfExpression iTypeOfExpression = expression as ITypeOfExpression;
                if (iTypeOfExpression != null)
                {
                    this.WriteTypeOfExpression(iTypeOfExpression);
                    return;
                }

                ISnippetExpression iSnippetExpression = expression as ISnippetExpression;
                if (iSnippetExpression != null)
                {
                    this.WriteSnippetExpression(iSnippetExpression);
                    return;
                }

                IUnaryExpression iUnaryExpression = expression as IUnaryExpression;
                if (iUnaryExpression != null)
                {
                    this.WriteUnaryExpression(iUnaryExpression);
                    return;
                }

                IObjectCreateExpression iObjectCreateExpression = expression as IObjectCreateExpression;
                if (iObjectCreateExpression != null)
                {
                    this.WriteObjectCreateExpression(iObjectCreateExpression);
                    return;
                }

                IVariableReferenceExpression iVariableReferenceExpression = expression as IVariableReferenceExpression;
                if (iVariableReferenceExpression != null)
                {
                    this.WriteVariableReferenceExpression(iVariableReferenceExpression);
                    return;
                }

                IThisReferenceExpression expression12 = expression as IThisReferenceExpression;
                if (expression12 != null)
                {
                    this.WriteThisReferenceExpression(expression12);
                    return;
                }

                ITryCastExpression iTryCastExpression = expression as ITryCastExpression;
                if (iTryCastExpression != null)
                {
                    this.WriteTryCastExpression(iTryCastExpression);
                    return;
                }

                IConditionExpression expression9 = expression as IConditionExpression;
                if (expression9 != null)
                {
                    this.WriteConditionExpression(expression9);
                    return;
                }

                IFieldReferenceExpression iFieldReferenceExpression = expression as IFieldReferenceExpression;
                if (iFieldReferenceExpression != null)
                {
                    this.WriteFieldReferenceExpression(iFieldReferenceExpression);
                    return;
                }

                IPropertyIndexerExpression iPropertyIndexerExpression = expression as IPropertyIndexerExpression;
                if (iPropertyIndexerExpression != null)
                {
                    this.WritePropertyIndexerExpression(iPropertyIndexerExpression);
                    return;
                }

                ITypeReferenceExpression iTypeReferenceExpression = expression as ITypeReferenceExpression;
                if (iTypeReferenceExpression != null)
                {
                    this.WriteTypeReferenceExpression(iTypeReferenceExpression);
                    return;
                }

                IMethodReferenceExpression iMethodReferenceExpression = expression as IMethodReferenceExpression;
                if (iMethodReferenceExpression != null)
                {
                    this.WriteMethodReferenceExpression(iMethodReferenceExpression);
                    return;
                }

                IPropertyReferenceExpression iPropertyReferenceExpression = expression as IPropertyReferenceExpression;
                if (iPropertyReferenceExpression != null)
                {
                    this.WritePropertyReferenceExpression(iPropertyReferenceExpression);
                    return;
                }

                ICastExpression expression5 = expression as ICastExpression;
                if (expression5 != null)
                {
                    this.WriteCastExpression(expression5);
                    return;
                }

                ICanCastExpression iCanCastExpression = expression as ICanCastExpression;
                if (iCanCastExpression != null)
                {
                    this.WriteCanCastExpression(iCanCastExpression);
                    return;
                }

                ICastExpression iCastExpression = expression as ICastExpression;
                if (iCastExpression != null)
                {
                    this.WriteCastExpression(iCastExpression);
                    return;
                }

                ILiteralExpression literalExpression = expression as ILiteralExpression;
                if (literalExpression != null)
                {
                    this.WriteLiteralExpression(literalExpression);
                    return;
                }

                IBinaryExpression iBinaryExpression = expression as IBinaryExpression;
                if (iBinaryExpression != null)
                {
                    mwg.Reflector.CppCli.ExpressionWriter.WriteExpression(this, expression, true);
                    //this.WriteBinaryExpression(iBinaryExpression);
                    return;
                }

                IArrayIndexerExpression expression30 = expression as IArrayIndexerExpression;
                if (expression30 != null)
                {
                    this.WriteArrayIndexerExpression(expression30);
                    return;
                }

                IAddressDereferenceExpression expression29 = expression as IAddressDereferenceExpression;
                if (expression29 != null)
                {
                    this.WriteAddressDereferenceExpression(expression29);
                    return;
                }

                IAddressOfExpression expression28 = expression as IAddressOfExpression;
                if (expression28 != null)
                {
                    this.WriteAddressOfExpression(expression28);
                    return;
                }

                IArgumentListExpression expression25 = expression as IArgumentListExpression;
                if (expression25 != null)
                {
                    this.WriteArgumentListExpression(expression25);
                    return;
                }

                IBaseReferenceExpression iBaseReferenceExpression = expression as IBaseReferenceExpression;
                if (iBaseReferenceExpression != null)
                {
                    this.WriteBaseReferenceExpression(iBaseReferenceExpression);
                    return;
                }

                IArgumentReferenceExpression expression13 = expression as IArgumentReferenceExpression;
                if (expression13 != null)
                {
                    this.WriteArgumentReferenceExpression(expression13);
                    return;
                }

                IArrayCreateExpression expression10 = expression as IArrayCreateExpression;
                if (expression10 != null)
                {
                    this.WriteArrayCreateExpression(expression10);
                    return;
                }

                IAssignExpression iAssignExpression = expression as IAssignExpression;
                if (iAssignExpression != null)
                {
                    this.WriteAssignExpression(iAssignExpression);
                    return;
                }

                IBlockExpression expression2 = expression as IBlockExpression;
                if (expression2 != null)
                {
                    this.WriteBlockExpression(expression2);
                    return;
                }
#pragma warning restore 612

                this.Write(expression.ToString());
#endif
            }
Example #13
0
        protected void ProcessAssign(IExpression target, IExpression rhs, ref bool shouldDelete)
        {
            IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(target);

            if (ivd == null)
            {
                return;
            }
            if (rhs is IArrayCreateExpression)
            {
                IArrayCreateExpression iace = (IArrayCreateExpression)rhs;
                bool zeroLength             = iace.Dimensions.All(dimExpr =>
                                                                  (dimExpr is ILiteralExpression) && ((ILiteralExpression)dimExpr).Value.Equals(0));
                if (!zeroLength && iace.Initializer == null)
                {
                    return; // variable will have assignments to elements
                }
            }
            bool firstTime = !variablesAssigned.Contains(ivd);

            variablesAssigned.Add(ivd);
            bool isInferred   = context.InputAttributes.Has <IsInferred>(ivd);
            bool isStochastic = CodeRecognizer.IsStochastic(context, ivd);

            if (!isStochastic)
            {
                return;
            }
            VariableInformation vi            = VariableInformation.GetVariableInformation(context, ivd);
            Containers          defContainers = context.InputAttributes.Get <Containers>(ivd);
            int        ancIndex = defContainers.GetMatchingAncestorIndex(context);
            Containers missing  = defContainers.GetContainersNotInContext(context, ancIndex);
            // definition of a stochastic variable
            IExpression lhs = target;

            if (lhs is IVariableDeclarationExpression)
            {
                lhs = Builder.VarRefExpr(ivd);
            }
            IExpression defExpr = lhs;

            if (firstTime && isStochastic)
            {
                // Create a ChannelInfo attribute for use by later transforms, e.g. MessageTransform
                ChannelInfo defChannel = ChannelInfo.DefChannel(vi);
                defChannel.decl = ivd;
                context.OutputAttributes.Set(ivd, defChannel);
            }
            bool       isDerived = context.InputAttributes.Has <DerivedVariable>(ivd);
            IAlgorithm algorithm = this.algorithmDefault;
            Algorithm  algAttr   = context.InputAttributes.Get <Algorithm>(ivd);

            if (algAttr != null)
            {
                algorithm = algAttr.algorithm;
            }
            if (algorithm is VariationalMessagePassing && ((VariationalMessagePassing)algorithm).UseDerivMessages && isDerived && firstTime)
            {
                vi.DefineAllIndexVars(context);
                IList <IStatement>   stmts     = Builder.StmtCollection();
                IVariableDeclaration derivDecl = vi.DeriveIndexedVariable(stmts, context, ivd.Name + "_deriv");
                context.OutputAttributes.Set(ivd, new DerivMessage(derivDecl));
                ChannelInfo derivChannel = ChannelInfo.DefChannel(vi);
                derivChannel.decl = derivDecl;
                context.OutputAttributes.Set(derivChannel.decl, derivChannel);
                context.OutputAttributes.Set(derivChannel.decl, new DescriptionAttribute("deriv of '" + ivd.Name + "'"));
                // Add the declarations
                stmts = Containers.WrapWithContainers(stmts, missing.outputs);
                context.AddStatementsBeforeAncestorIndex(ancIndex, stmts);
            }
            bool isPointEstimate = context.InputAttributes.Has <PointEstimate>(ivd);

            if (this.analysis.variablesExcludingVariableFactor.Contains(ivd))
            {
                this.variablesLackingVariableFactor.Add(ivd);
                // ivd will get a marginal channel in ConvertMethodInvoke
                useOfVariable[ivd] = ivd;
                return;
            }
            if (isDerived && !isInferred && !isPointEstimate)
            {
                return;
            }

            IExpression useExpr2 = null;

            if (firstTime)
            {
                // create marginal and use channels
                vi.DefineAllIndexVars(context);
                IList <IStatement> stmts = Builder.StmtCollection();

                CreateMarginalChannel(ivd, vi, stmts);
                if (isStochastic)
                {
                    CreateUseChannel(ivd, vi, stmts);
                    context.InputAttributes.Set(useOfVariable[ivd], defContainers);
                }

                // Add the declarations
                stmts = Containers.WrapWithContainers(stmts, missing.outputs);
                context.AddStatementsBeforeAncestorIndex(ancIndex, stmts);
            }
            if (isStochastic && !useOfVariable.ContainsKey(ivd))
            {
                Error("cannot find use channel of " + ivd);
                return;
            }
            IExpression  marginalExpr = Builder.ReplaceVariable(lhs, ivd, marginalOfVariable[ivd]);
            IExpression  useExpr      = isStochastic ? Builder.ReplaceVariable(lhs, ivd, useOfVariable[ivd]) : marginalExpr;
            InitialiseTo it           = context.InputAttributes.Get <InitialiseTo>(ivd);

            Type[] genArgs = new Type[] { defExpr.GetExpressionType() };
            if (rhs is IMethodInvokeExpression)
            {
                IMethodInvokeExpression imie = (IMethodInvokeExpression)rhs;
                if (Recognizer.IsStaticGenericMethod(imie, new Func <PlaceHolder, PlaceHolder>(Clone.Copy)) && ancIndex < context.InputStack.Count - 2)
                {
                    IExpression          arg  = imie.Arguments[0];
                    IVariableDeclaration ivd2 = Recognizer.GetVariableDeclaration(arg);
                    if (ivd2 != null && context.InputAttributes.Get <MarginalPrototype>(ivd) == context.InputAttributes.Get <MarginalPrototype>(ivd2))
                    {
                        // if a variable is a copy, use the original expression since it will give more precise dependencies.
                        defExpr      = arg;
                        shouldDelete = true;
                        bool makeClone = false;
                        if (makeClone)
                        {
                            VariableInformation         vi2      = VariableInformation.GetVariableInformation(context, ivd2);
                            IList <IStatement>          stmts    = Builder.StmtCollection();
                            List <IList <IExpression> > indices  = Recognizer.GetIndices(defExpr);
                            IVariableDeclaration        useDecl2 = vi2.DeriveIndexedVariable(stmts, context, ivd2.Name + "_use", indices);
                            useExpr2 = Builder.VarRefExpr(useDecl2);
                            Containers defContainers2 = context.InputAttributes.Get <Containers>(ivd2);
                            int        ancIndex2      = defContainers2.GetMatchingAncestorIndex(context);
                            Containers missing2       = defContainers2.GetContainersNotInContext(context, ancIndex2);
                            stmts = Containers.WrapWithContainers(stmts, missing2.outputs);
                            context.AddStatementsBeforeAncestorIndex(ancIndex2, stmts);
                            context.InputAttributes.Set(useDecl2, defContainers2);

                            // TODO: call CreateUseChannel
                            ChannelInfo usageChannel = ChannelInfo.UseChannel(vi2);
                            usageChannel.decl = useDecl2;
                            context.InputAttributes.CopyObjectAttributesTo <InitialiseTo>(vi.declaration, context.OutputAttributes, useDecl2);
                            context.InputAttributes.CopyObjectAttributesTo <DerivMessage>(vi.declaration, context.OutputAttributes, useDecl2);
                            context.OutputAttributes.Set(useDecl2, usageChannel);
                            //context.OutputAttributes.Set(useDecl2, new DescriptionAttribute("use of '" + ivd.Name + "'"));
                            context.OutputAttributes.Remove <InitialiseTo>(vi.declaration);

                            IExpression copyExpr = Builder.StaticGenericMethod(
                                new Func <PlaceHolder, PlaceHolder>(Clone.Copy), genArgs, useExpr2);
                            var copyStmt = Builder.AssignStmt(useExpr, copyExpr);
                            context.AddStatementAfterCurrent(copyStmt);
                        }
                    }
                }
            }

            // Add the variable factor
            IExpression variableFactorExpr;
            bool        isGateExitRandom = context.InputAttributes.Has <VariationalMessagePassing.GateExitRandomVariable>(ivd);

            if (isGateExitRandom)
            {
                variableFactorExpr = Builder.StaticGenericMethod(
                    new Models.FuncOut <PlaceHolder, PlaceHolder, PlaceHolder>(Gate.ExitingVariable),
                    genArgs, defExpr, marginalExpr);
            }
            else
            {
                Delegate d = algorithm.GetVariableFactor(isDerived, it != null);
                if (isPointEstimate)
                {
                    d = new Models.FuncOut <PlaceHolder, PlaceHolder, PlaceHolder>(Clone.VariablePoint);
                }
                if (it == null)
                {
                    variableFactorExpr = Builder.StaticGenericMethod(d, genArgs, defExpr, marginalExpr);
                }
                else
                {
                    IExpression initExpr = Builder.ReplaceExpression(lhs, Builder.VarRefExpr(ivd), it.initialMessagesExpression);
                    variableFactorExpr = Builder.StaticGenericMethod(d, genArgs, defExpr, initExpr, marginalExpr);
                }
            }
            context.InputAttributes.CopyObjectAttributesTo <GivePriorityTo>(ivd, context.OutputAttributes, variableFactorExpr);
            context.InputAttributes.CopyObjectAttributesTo <Algorithm>(ivd, context.OutputAttributes, variableFactorExpr);
            if (isStochastic)
            {
                context.OutputAttributes.Set(variableFactorExpr, new IsVariableFactor());
            }
            var assignStmt = Builder.AssignStmt(useExpr2 == null ? useExpr : useExpr2, variableFactorExpr);

            context.AddStatementAfterCurrent(assignStmt);
        }
Example #14
0
 // Shallow copy array creations for efficiency
 protected override IExpression ConvertArrayCreate(IArrayCreateExpression iace)
 {
     return iace;
 }
Example #15
0
 public object Evaluate(IExpression expr)
 {
     if (expr is IObjectCreateExpression)
     {
         return(Evaluate((IObjectCreateExpression)expr));
     }
     else if (expr is ILiteralExpression)
     {
         return(((ILiteralExpression)expr).Value);
     }
     else if (expr is ICastExpression)
     {
         return(Evaluate(((ICastExpression)expr).Expression));
     }
     else if (expr is ICheckedExpression)
     {
         return(Evaluate(((ICheckedExpression)expr).Expression));
     }
     else if (expr is IBinaryExpression)
     {
         IBinaryExpression ibe   = (IBinaryExpression)expr;
         object            left  = Evaluate(ibe.Left);
         object            right = Evaluate(ibe.Right);
         Type type = left.GetType();
         return(Microsoft.ML.Probabilistic.Compiler.Reflection.Invoker.InvokeStatic(type, binaryOperatorNames[(int)ibe.Operator], left, right));
     }
     else if (expr is IUnaryExpression)
     {
         IUnaryExpression iue    = (IUnaryExpression)expr;
         object           target = Evaluate(iue.Expression);
         Type             type   = target.GetType();
         return(Microsoft.ML.Probabilistic.Compiler.Reflection.Invoker.InvokeStatic(type, unaryOperatorNames[(int)iue.Operator], target));
     }
     else if (expr is IMethodInvokeExpression)
     {
         IMethodInvokeExpression imie = (IMethodInvokeExpression)expr;
         object[] args = EvaluateAll(imie.Arguments);
         return(Invoke(imie.Method, args));
     }
     else if (expr is IArrayCreateExpression)
     {
         IArrayCreateExpression iace = (IArrayCreateExpression)expr;
         Type  t    = Builder.ToType(iace.Type);
         int[] lens = new int[iace.Dimensions.Count];
         for (int i = 0; i < lens.Length; i++)
         {
             lens[i] = (int)Evaluate(iace.Dimensions[i]);
         }
         // TODO: evaluate initializer
         if (iace.Initializer != null)
         {
             throw new NotImplementedException("IArrayCreateExpression has an initializer block");
         }
         return(Array.CreateInstance(t, lens));
     }
     else if (expr is IFieldReferenceExpression)
     {
         IFieldReferenceExpression ifre = (IFieldReferenceExpression)expr;
         if (ifre.Target is ITypeReferenceExpression)
         {
             ITypeReferenceExpression itre = (ITypeReferenceExpression)ifre.Target;
             Type      type = Builder.ToType(itre.Type);
             FieldInfo info = type.GetField(ifre.Field.Name);
             return(info.GetValue(null));
         }
         else
         {
             object    target = Evaluate(ifre.Target);
             FieldInfo info   = target.GetType().GetField(ifre.Field.Name);
             return(info.GetValue(target));
         }
     }
     else
     {
         throw new InferCompilerException("Could not evaluate: " + expr);
     }
 }
Example #16
0
        protected override IExpression ConvertArrayCreate(IArrayCreateExpression iace)
        {
            IArrayCreateExpression ace = (IArrayCreateExpression)base.ConvertArrayCreate(iace);
            IAssignExpression      iae = context.FindAncestor <IAssignExpression>();

            if (iae == null)
            {
                return(ace);
            }
            if (iae.Expression != iace)
            {
                return(ace);
            }
            if (iace.Initializer != null)
            {
                var  exprs             = iace.Initializer.Expressions;
                bool expandInitializer = !AllElementsAreLiteral(exprs);
                if (expandInitializer)
                {
                    // convert the initializer to a list of assignment statements to literal indices
                    bool wasConvertingArrayCreate = convertingArrayCreate;
                    if (!wasConvertingArrayCreate)
                    {
                        arrayCreateStmts.Clear();
                    }
                    convertingArrayCreate = true;
                    IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(iae.Target);
                    // Sets the size of this variable at this array depth
                    int           depth    = Recognizer.GetIndexingDepth(iae.Target);
                    IExpression[] dimExprs = new IExpression[ace.Dimensions.Count];
                    for (int i = 0; i < dimExprs.Length; i++)
                    {
                        dimExprs[i] = ace.Dimensions[i];
                    }
                    List <IList <IExpression> > indices = Recognizer.GetIndices(iae.Target);
                    // for a multi-dimensional array, exprs will contain IBlockExpressions
                    // dimExprs must be ILiteralExpressions
                    int[] dims         = Util.ArrayInit(dimExprs.Length, i => (int)((ILiteralExpression)dimExprs[i]).Value);
                    int[] strides      = StringUtil.ArrayStrides(dims);
                    int   elementCount = strides[0] * dims[0];
                    var   target       = Builder.JaggedArrayIndex(Builder.VarRefExpr(ivd), indices);
                    int[] mIndex       = new int[dims.Length];
                    for (int linearIndex = elementCount - 1; linearIndex >= 0; linearIndex--)
                    {
                        StringUtil.LinearIndexToMultidimensionalIndex(linearIndex, strides, mIndex);
                        var indexExprs = Util.ArrayInit(mIndex.Length, i => Builder.LiteralExpr(mIndex[i]));
                        var lhs        = Builder.ArrayIndex(target, indexExprs);
                        var expr       = GetInitializerElement(exprs, mIndex);
                        var assignStmt = Builder.AssignStmt(lhs, expr);
                        var st         = ConvertStatement(assignStmt);
                        arrayCreateStmts.Push(st);
                    }
                    ace.Initializer       = null;
                    convertingArrayCreate = wasConvertingArrayCreate;
                    if (!wasConvertingArrayCreate)
                    {
                        context.AddStatementsAfterCurrent(arrayCreateStmts);
                    }
                }
            }
            return(ace);

            bool AllElementsAreLiteral(IList <IExpression> exprs)
            {
                foreach (var expr in exprs)
                {
                    if (expr is IBlockExpression ibe)
                    {
                        if (!AllElementsAreLiteral(ibe.Expressions))
                        {
                            return(false);
                        }
                    }
                    else if (!(expr is ILiteralExpression))
                    {
                        return(false);
                    }
                }
                return(true);
            }

            IExpression GetInitializerElement(IList <IExpression> exprs, int[] mIndex, int dim = 0)
            {
                var expr = exprs[mIndex[dim]];

                if (dim == mIndex.Length - 1)
                {
                    return(expr);
                }
                else
                {
                    var blockExpr = (IBlockExpression)expr;
                    return(GetInitializerElement(blockExpr.Expressions, mIndex, dim + 1));
                }
            }
        }
 private void WriteArrayCreateExpression(IArrayCreateExpression expression, IFormatter formatter)
 {
     if (expression.Initializer != null)
     {
         this.WriteExpression(expression.Initializer, formatter);
     }
     else
     {
         if (expression.Dimensions.Count == 1 && (expression.Dimensions[0] is ILiteralExpression) && ((ILiteralExpression)expression.Dimensions[0]).Value.Equals(0))
         {
             formatter.Write("[]");
         }
         else
         {
             formatter.Write("Array");
             formatter.Write("(");
             this.WriteExpressionList(expression.Dimensions, formatter);
             formatter.Write(")");
         }
     }
 }
 public virtual void VisitArrayCreateExpression(IArrayCreateExpression value)
 {
     this.VisitType(value.Type);
     this.VisitExpression(value.Initializer);
     this.VisitExpressionCollection(value.Dimensions);
 }
 public virtual void VisitArrayCreateExpression(IArrayCreateExpression value)
 {
     VisitType(value.Type);
     VisitExpression(value.Initializer);
     VisitExpressionCollection(value.Dimensions);
 }