private IPropertyMember InitializeResourceManager() { //Declare the resource manager field. this.resourceManagerDataMember = this.Fields.AddNew(new TypedName("_resourceManager", typeof(ResourceManager))); //The property... this.resourceManager = this.Properties.AddNew(new TypedName("ResourceManager", resourceManagerDataMember.FieldType), true, false); //Full resolution. resourceManagerDataMember.FieldType.ResolutionOptions = TypeReferenceResolveOptions.GlobalType; IFieldReferenceExpression resourceManagerDataMemberRef = resourceManagerDataMember.GetReference(); //Check if it's null, IConditionStatement ics = resourceManager.GetPart.IfThen((Expression.Expression)resourceManagerDataMemberRef == PrimitiveExpression.NullValue); //If it is and the parent is a namespace, then use the assembly's resource. if (this.ParentTarget is INameSpaceDeclaration || this.parentTarget is IIntermediateProject) { ics.Assign(resourceManagerDataMemberRef, new CreateNewObjectExpression(resourceManagerDataMember.FieldType, new PrimitiveExpression("Resources"), (new TypeOfExpression(this)).GetProperty("Assembly"))); } //Otherwise the resource is for the contianing type. else if (this.parentTarget is IDeclaredType) { ics.Assign(resourceManagerDataMemberRef, new CreateNewObjectExpression(resourceManagerDataMember.FieldType, new TypeOfExpression(this))); } //Yield the return of the data member. resourceManager.GetPart.Return(resourceManagerDataMemberRef); return(this.resourceManager); }
private Containers RemoveReferencesTo(Containers containers, IExpression expr) { Containers result = new Containers(); for (int i = 0; i < containers.inputs.Count; i++) { IStatement container = containers.inputs[i]; if (container is IForStatement) { IForStatement ifs = container as IForStatement; if (Builder.ContainsExpression(ifs.Condition, expr)) { continue; } } else if (container is IConditionStatement) { IConditionStatement ics = (IConditionStatement)container; if (Builder.ContainsExpression(ics.Condition, expr)) { continue; } } result.inputs.Add(container); result.outputs.Add(containers.outputs[i]); } return(result); }
private void ModifyStatement(IStatement ist, IStatementBlock isb) { if (isb is IfBlock) { IfBlock ib = (IfBlock)isb; var condVar = ib.ConditionVariable; if (!negatedConditionVariables.Contains(condVar)) { if (condVar.definition != null) { MethodInvoke mi = condVar.definition; if (mi.method.Equals(new Func <int, int, bool>(Factor.AreEqual).Method)) { if (mi.Arguments[1] is Variable) { Variable arg1 = (Variable)mi.Arguments[1]; if (arg1.IsObserved || arg1.IsLoopIndex) { // convert 'if(vbool1)' into 'if(x==value)' where value is observed (or a loop index) and vbool1 is never negated. // if vbool1 is negated, then we cannot make this substitution since we need to match the corresponding 'if(!vbool1)' condition. IConditionStatement ics = (IConditionStatement)ist; ics.Condition = Builder.BinaryExpr(mi.Arguments[0].GetExpression(), BinaryOperator.ValueEquality, arg1.GetExpression()); } } } } } } }
protected override IStatement ConvertCondition(IConditionStatement ics) { // innermostConditionBlock will be set when transforming the body. innermostConditionBlock = null; AnalyzeCondition(ics.Condition); IConditionStatement cs = Builder.CondStmt(); context.SetPrimaryOutput(cs); cs.Condition = ics.Condition; cs.Then = ConvertBlock(ics.Then); if (ics.Else != null) { cs.Else = ConvertBlock(ics.Else); } if (cs.Then.Statements.Count == 0 && (cs.Else == null || cs.Else.Statements.Count == 0)) { return(null); } // if innermostConditionBlock is null after transforming the body, then this is the innermost. // we cannot return the original ics in this case since innermostConditionBlock can be modified by parents. if (innermostConditionBlock == null) { innermostConditionBlock = cs.Then.Statements; } else if (!ShallowCopy && ReferenceEquals(cs.Condition, ics.Condition) && ReferenceEquals(cs.Then, ics.Then) && ReferenceEquals(cs.Else, ics.Else)) { return(ics); } context.InputAttributes.CopyObjectAttributesTo(ics, context.OutputAttributes, cs); return(cs); }
public static void ForEachStatement(IEnumerable <IStatement> isc, Action <IWhileStatement> beginWhile, Action <IWhileStatement> endWhile, Action <IConditionStatement> beginFirstIterPost, Action <IConditionStatement> endFirstIterPost, Action <IStatement> action) { foreach (IStatement stmt in isc) { if (stmt is IWhileStatement) { IWhileStatement iws = (IWhileStatement)stmt; beginWhile(iws); ForEachStatement(iws.Body.Statements, beginWhile, endWhile, beginFirstIterPost, endFirstIterPost, action); endWhile(iws); continue; } else if (stmt is IConditionStatement) { IConditionStatement ics = (IConditionStatement)stmt; bool testsIteration = Recognizer.GetVariables(ics.Condition).Any(ivd => (ivd.Name == "iteration")); if (testsIteration) { beginFirstIterPost(ics); ForEachStatement(ics.Then.Statements, beginWhile, endWhile, beginFirstIterPost, endFirstIterPost, action); endFirstIterPost(ics); continue; } // fall through } action(stmt); } }
internal static Containers SortStochasticConditionals(Containers containers, BasicTransformContext context) { Containers result = new Containers(); Containers conditionals = new Containers(); for (int i = 0; i < containers.inputs.Count; i++) { IStatement container = containers.inputs[i]; if (container is IConditionStatement) { IConditionStatement ics = (IConditionStatement)container; if (CodeRecognizer.IsStochastic(context, ics.Condition)) { conditionals.inputs.Add(container); conditionals.outputs.Add(containers.outputs[i]); continue; } } result.inputs.Add(container); result.outputs.Add(containers.outputs[i]); } for (int i = 0; i < conditionals.inputs.Count; i++) { result.inputs.Add(conditionals.inputs[i]); result.outputs.Add(conditionals.outputs[i]); } return(result); }
/// <summary> /// Create a clone of prototype with an empty body. /// </summary> /// <param name="prototype"></param> /// <returns></returns> internal static IStatement CreateContainer(IStatement prototype) { if (prototype is IForStatement) { IForStatement loop = (IForStatement)prototype; IForStatement ifs = Builder.ForStmt(loop); ifs.Initializer = loop.Initializer; ifs.Condition = loop.Condition; ifs.Increment = loop.Increment; ifs.Body = Builder.BlockStmt(); return(ifs); } else if (prototype is IConditionStatement) { IConditionStatement cond = (IConditionStatement)prototype; return(Builder.CondStmt(cond.Condition, Builder.BlockStmt())); } else if (prototype is IRepeatStatement) { IRepeatStatement irs = (IRepeatStatement)prototype; return(Builder.RepeatStmt(irs.Count)); } else { throw new NotImplementedException("unrecognized container: " + prototype); } }
public override bool Equals(object obj) { if (this == obj) { return(true); } IConditionStatement statement = obj as IConditionStatement; if (statement == null) { return(false); } if ((Condition == null) ? (Condition != statement.Condition) : !Condition.Equals(statement.Condition)) { return(false); } if ((Then == null) ? (Then != statement.Then) : !Then.Equals(statement.Then)) { return(false); } if ((Else == null) ? (Else != statement.Else) : !Else.Equals(statement.Else)) { return(false); } return(true); }
// Modifies affectingVariables. internal static bool ContainerAffectsVariables(IStatement container, Set <IVariableDeclaration> affectingVariables) { if (container is IForStatement) { IForStatement ifs2 = (IForStatement)container; if (affectingVariables.Contains(Recognizer.LoopVariable(ifs2))) { // all variables in the loop bounds become affecting variables. affectingVariables.AddRange( Recognizer.GetVariables(Recognizer.LoopStartExpression(ifs2)).Concat( Recognizer.GetVariables(ifs2.Condition) )); return(true); } return(false); } else if (container is IConditionStatement) { IConditionStatement ics = (IConditionStatement)container; // if the condition refers to an affecting variable, then it is a parent. bool isParent = Recognizer.GetVariables(ics.Condition).Any(affectingVariables.Contains); if (isParent) { // all variables in the condition become affecting variables, // since they change the outcome of the condition and therefore the bounds of ifs. affectingVariables.AddRange(Recognizer.GetVariables(ics.Condition)); return(true); } return(false); } else { throw new NotImplementedException($"Unrecognized container type: {StringUtil.TypeToString(container.GetType())}"); } }
protected override IStatement ConvertCondition(IConditionStatement ics) { IConditionStatement cs = Builder.CondStmt(); cs.Condition = ConvertExpression(ics.Condition); if (cs.Condition is ILiteralExpression) { bool value = (bool)((ILiteralExpression)cs.Condition).Value; if (value) { if (ics.Then != null) { foreach (IStatement st in ics.Then.Statements) { IStatement ist = ConvertStatement(st); if (ist != null) { context.AddStatementBeforeCurrent(ist); } } } } else { if (ics.Else != null) { foreach (IStatement st in ics.Else.Statements) { IStatement ist = ConvertStatement(st); if (ist != null) { context.AddStatementBeforeCurrent(ist); } } } } return(null); } context.SetPrimaryOutput(cs); IForStatement loop; ConditionBinding binding = GateTransform.GetConditionBinding(cs.Condition, context, out loop); int startIndex = conditionContext.Count; conditionContext.Add(binding); cs.Then = ConvertBlock(ics.Then); if (ics.Else != null) { conditionContext.RemoveRange(startIndex, conditionContext.Count - startIndex); binding = binding.FlipCondition(); conditionContext.Add(binding); cs.Else = ConvertBlock(ics.Else); } conditionContext.RemoveRange(startIndex, conditionContext.Count - startIndex); if (cs.Then.Statements.Count == 0 && (cs.Else == null || cs.Else.Statements.Count == 0)) { return(null); } return(cs); }
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); }
/// <summary> /// True if the containers match, ignoring the statements in their bodies. /// </summary> /// <param name="st1"></param> /// <param name="st2"></param> /// <param name="allowBrokenLoops"></param> /// <param name="ignoreLoopDirection"></param> /// <returns></returns> internal static bool ContainersAreEqual(IStatement st1, IStatement st2, bool allowBrokenLoops = false, bool ignoreLoopDirection = false) { if (ReferenceEquals(st1, st2)) { return(true); } if (st1 is IForStatement) { IForStatement ifs1 = (IForStatement)st1; if (st2 is IForStatement) { IForStatement ifs2 = (IForStatement)st2; if (ignoreLoopDirection && Recognizer.IsForwardLoop(ifs1) != Recognizer.IsForwardLoop(ifs2)) { ifs2 = (IForStatement)CreateContainer(ifs2); Recognizer.ReverseLoopDirection(ifs2); } return(ifs1.Initializer.Equals(ifs2.Initializer) && ifs1.Condition.Equals(ifs2.Condition) && ifs1.Increment.Equals(ifs2.Increment) && (allowBrokenLoops || ((ifs1 is IBrokenForStatement) == (ifs2 is IBrokenForStatement)))); } else { return(false); } } else if (st1 is IConditionStatement) { IConditionStatement ics1 = (IConditionStatement)st1; if (st2 is IConditionStatement) { IConditionStatement ics2 = (IConditionStatement)st2; return(ics1.Condition.Equals(ics2.Condition)); } else { return(false); } } else if (st1 is IRepeatStatement) { IRepeatStatement irs1 = (IRepeatStatement)st1; if (st2 is IRepeatStatement) { IRepeatStatement irs2 = (IRepeatStatement)st2; return(irs1.Count.Equals(irs2.Count)); } else { return(false); } } else { return(st1 == st2); } }
protected override IStatement ConvertCondition(IConditionStatement ics) { context.SetPrimaryOutput(ics); ConvertExpression(ics.Condition); openContainers.Push(ics); ConvertBlock(ics.Then); openContainers.Pop(); return(ics); }
/// <summary> /// Gets a statement for the entire block, and a pointer to its body. /// </summary> /// <param name="innerBlock">On return, a pointer to the body of the block.</param> /// <returns></returns> internal override IStatement GetStatement(out IList <IStatement> innerBlock) { IConditionStatement cs = Builder.CondStmt(); cs.Condition = GetConditionExpression(); cs.Then = Builder.BlockStmt(); innerBlock = cs.Then.Statements; return(cs); }
protected override IStatement ConvertCondition(IConditionStatement ics) { var copy = (IConditionStatement)base.ConvertCondition(ics); if (NeedsIntermediate(copy.Condition) && !(copy.Condition is IUnaryExpression && ((IUnaryExpression)copy.Condition).Operator == UnaryOperator.BooleanNot)) { // TODO this breaks things //copy.Condition = MakeIntermediateVariable(copy.Condition); } return(copy); }
internal static Containers RemoveInvalidConditions(Containers containers, BasicTransformContext context) { Containers result = new Containers(); for (int i = 0; i < containers.inputs.Count; i++) { IStatement container = containers.inputs[i]; if (container is IConditionStatement ics) { IExpression condition = ics.Condition; if (condition is IBinaryExpression ibe && ibe.Operator == BinaryOperator.BooleanAnd) { // split the condition into conjuncts List <IExpression> conditions = new List <IExpression>(); IExpression newCondition = null; bool changed = false; ForEachConjunct(condition, delegate(IExpression expr) { if (ContainsExpression(containers.inputs, context, expr)) { if (newCondition == null) { newCondition = expr; } else { newCondition = Builder.BinaryExpr(BinaryOperator.BooleanAnd, newCondition, expr); } } else { changed = true; } }); if (changed) { if (newCondition != null) { IConditionStatement cs = Builder.CondStmt(newCondition, Builder.BlockStmt()); result.inputs.Add(cs); result.outputs.Add(cs); } continue; } } else { if (!ContainsExpression(containers.inputs, context, condition)) { continue; } } }
protected override IStatement ConvertCondition(IConditionStatement ics) { variablesInExpression.Clear(); ConvertExpression(ics.Condition); var variablesAdded = (Set <IVariableDeclaration>)variablesInExpression.Clone(); unbrokenLoopVars.Remove(variablesInExpression); ConvertBlock(ics.Then); if (ics.Else != null) { ConvertBlock(ics.Else); } return(ics); }
/// <summary> /// Analyze in reverse order. /// </summary> /// <param name="ics"></param> /// <returns></returns> protected override IStatement ConvertCondition(IConditionStatement ics) { if (ics.Else != null) { throw new Exception("ics.Else != null"); } var liveFieldsAtEnd = (Set <IFieldDeclaration>)liveFields.Clone(); var liveVariablesAtEnd = (Set <IVariableDeclaration>)liveVariables.Clone(); ConvertBlock(ics.Then); ConvertExpression(ics.Condition); // merge the live variables at end since the condition may not be taken. liveFields.AddRange(liveFieldsAtEnd); liveVariables.AddRange(liveVariablesAtEnd); return(ics); }
public static int ContainerGetHashCode(IStatement st) { if (st is IForStatement) { IForStatement ifs = (IForStatement)st; return(ifs.Initializer.GetHashCode()); } else if (st is IConditionStatement) { IConditionStatement ics = (IConditionStatement)st; return(ics.Condition.GetHashCode()); } else { return(st.GetHashCode()); } }
internal static List <ConditionBinding> GetBindings(BasicTransformContext context, IEnumerable <IStatement> containers) { List <ConditionBinding> bindings = new List <ConditionBinding>(); foreach (IStatement st in containers) { if (st is IConditionStatement) { IConditionStatement ics = (IConditionStatement)st; if (!CodeRecognizer.IsStochastic(context, ics.Condition)) { ConditionBinding binding = new ConditionBinding(ics.Condition); bindings.Add(binding); } } } return(bindings); }
private void FinishGivenOrConstant(Variable variable, object decl) { if (variable is IVariableArray iva) { // attach a VariableInformation attribute that holds the array sizes // this is needed because the array size never appears in the code IList <IVariableDeclaration[]> jaggedIndexVars; IList <IExpression[]> jaggedSizes; GetJaggedArrayIndicesAndSizes(iva, out jaggedIndexVars, out jaggedSizes); var vi = new VariableInformation(decl); vi.sizes.AddRange(jaggedSizes); vi.indexVars.AddRange(jaggedIndexVars); Attributes.Set(decl, vi); // see ModelTests.RangeWithConstantSizeTest bool addLengthConstraints = false; if (addLengthConstraints) { IExpression array = variable.GetExpression(); IExpression valueIsNotNull = Builder.BinaryExpr(array, BinaryOperator.ValueInequality, Builder.LiteralExpr(null)); IConditionStatement cs = Builder.CondStmt(valueIsNotNull, Builder.BlockStmt()); var constraint = new Action <int, int>(Microsoft.ML.Probabilistic.Factors.Constrain.Equal); Type arrayType = array.GetExpressionType(); int rank = vi.sizes[0].Length; //Util.GetElementType(arrayType, out rank); for (int i = 0; i < rank; i++) { IExpression lengthExpr; if (rank == 1) { lengthExpr = Builder.PropRefExpr(array, arrayType, arrayType.IsArray ? "Length" : "Count", typeof(int)); } else { lengthExpr = Builder.Method(array, typeof(Array).GetMethod("GetLength"), Builder.LiteralExpr(i)); } cs.Then.Statements.Add(Builder.ExprStatement( Builder.StaticMethod(constraint, lengthExpr, vi.sizes[0][i]))); } AddStatement(cs); } } }
protected override IStatement ConvertCondition(IConditionStatement ics) { ics = (IConditionStatement)base.ConvertCondition(ics); if (ics == null) { return(ics); } if ((ics.Else != null) && (ics.Else.Statements.Count > 0)) { Error("Unexpected else clause"); return(ics); } if (convertingBrokenLoop) { if (hoistAttributes) { IStatement st = ics.Then.Statements[0]; context.InputAttributes.CopyObjectAttributesTo(st, context.OutputAttributes, ics); } return(ics); } // We are not in an operator block, we need to cut the if across each statement foreach (IStatement st in ics.Then.Statements) { if (st is ICommentStatement) { // we do not need to keep ifs around comments context.AddStatementBeforeCurrent(st); continue; } IConditionStatement cs = Builder.CondStmt(); cs.Condition = ConvertExpression(ics.Condition); cs.Then = Builder.BlockStmt(); cs.Then.Statements.Add(st); context.AddStatementBeforeCurrent(cs); if (hoistAttributes) { context.InputAttributes.CopyObjectAttributesTo(st, context.OutputAttributes, cs); } context.InputAttributes.CopyObjectAttributesTo(ics, context.OutputAttributes, cs); } return(null); }
private static void WriteCondition(LanguageWriter w, IConditionStatement state) { #if EXTRA_TEMP using (NewBlock block3 = new NewBlock(w)) { w.WriteKeyword("if"); w.Write(" "); w.Write("("); ExpressionWriter.WriteExpression(w, state.Condition, false); w.Write(") "); using (NewBlock block2 = new NewBlock(w)) { WriteBracedStatement(w, state.Then); if (!IsBlank(state.Else)) { using (NewBlock block = new NewBlock(w)) { w.Write(" "); w.WriteKeyword("else"); w.Write(" "); WriteBracedStatement(w, state.Else); } } w.WriteLine(); } } #else w.WriteKeyword("if"); w.Write(" "); w.Write("("); ExpressionWriter.WriteExpression(w, state.Condition, false); w.Write(") "); WriteBracedStatement(w, state.Then); if (!IsBlank(state.Else)) { w.Write(" "); w.WriteKeyword("else"); w.Write(" "); WriteBracedStatement(w, state.Else); } w.WriteLine(); #endif }
public override void VisitConditionStatement(IConditionStatement value) { _formatter.WriteKeyword("if"); WriteWhitespace(); _formatter.Write("("); VisitExpression(value.Condition); _formatter.Write(")"); _formatter.WriteLine(); using (new IndentedCodeBlock(_formatter)) { VisitStatement(value.Then); } if (value.Else.Statements.Count != 0) { _formatter.WriteKeyword("else"); _formatter.WriteLine(); using (new IndentedCodeBlock(_formatter)) { VisitStatement(value.Else); } } }
protected override IStatement ConvertCondition(IConditionStatement ics) { ics = (IConditionStatement)base.ConvertCondition(ics); if (ics != null && ics.Then.Statements.Count == 1) { IStatement st = ics.Then.Statements[0]; if (st is IForStatement) { IForStatement ifs = (IForStatement)st; IVariableDeclaration loopVar = Recognizer.LoopVariable(ifs); bool isSequential = context.InputAttributes.Has <Sequential>(loopVar); if (isSequential) { ics.Then = ifs.Body; ifs.Body = Builder.BlockStmt(); ifs.Body.Statements.Add(ics); return(ifs); } } } return(ics); }
public void Rebuild() { if (this.autoMember != null) { this.declarationTarget.Properties.Remove(this.autoMember); this.autoMember.Dispose(); } if (this.dataMember != null) { this.declarationTarget.Fields.Remove(this.dataMember); this.dataMember.Dispose(); } switch (this.declarationTarget.GenerationType) { case ResourceGenerationType.GeneratedClass: this.autoMember = declarationTarget.Properties.AddNew(new TypedName(name, typeof(string)), true, false); this.autoMember.AccessLevel = DeclarationAccessLevel.Internal; this.namePrimitive = new PrimitiveExpression(name); this.autoMember.GetPart.Return(declarationTarget.ResourceManager.GetReference().GetMethod("GetString").Invoke(namePrimitive)); break; case ResourceGenerationType.GeneratedClassWithCache: this.dataMember = declarationTarget.Fields.AddNew(new TypedName(string.Format("__{0}_dm_", name), typeof(string))); this.autoMember = declarationTarget.Properties.AddNew(new TypedName(name, typeof(string)), true, false); this.dataMember.IsStatic = true; this.autoMember.IsStatic = true; this.dataMember.AccessLevel = DeclarationAccessLevel.Private; this.autoMember.AccessLevel = DeclarationAccessLevel.Internal; IFieldReferenceExpression dataMemberReference = dataMember.GetReference(); IConditionStatement ics = this.autoMember.GetPart.IfThen((Expression.Expression)dataMemberReference == PrimitiveExpression.NullValue); this.namePrimitive = new PrimitiveExpression(name); ics.Assign(dataMemberReference, declarationTarget.ResourceManager.GetReference().GetMethod("GetString").Invoke(namePrimitive)); this.autoMember.GetPart.Return(dataMemberReference); break; default: break; } }
internal static IList <IStatement> UnwrapStatement(IStatement ist, List <IStatement> containers) { if (ist is IForStatement) { containers.Add(ist); IForStatement ifs = (IForStatement)ist; if (ifs.Body.Statements.Count == 1) { return(UnwrapStatement(ifs.Body.Statements[0], containers)); } else { return(ifs.Body.Statements); } } else if (ist is IConditionStatement) { containers.Add(ist); IConditionStatement ics = (IConditionStatement)ist; if (ics.Then.Statements.Count == 1) { return(UnwrapStatement(ics.Then.Statements[0], containers)); } else { return(ics.Then.Statements); } } else { return(new List <IStatement>() { ist }); } }
/// <summary> /// Converts an if statement by deleting the outer statement and wrapping the inner statements. /// </summary> protected override IStatement ConvertCondition(IConditionStatement ics) { bool isStochastic = IsStochasticVariableReference(ics.Condition); if (!isStochastic) { return(base.ConvertCondition(ics)); } if ((ics.Else != null) && (ics.Else.Statements.Count > 0)) { Error("Unexpected else clause"); return(ics); } IConditionStatement oldParent = parent; parent = ics; ics = (IConditionStatement)base.ConvertCondition(ics); parent = oldParent; foreach (IStatement ist in ics.Then.Statements) { context.AddStatementBeforeCurrent(ist); } return(null); }
/// <summary> /// Analyse the condition body using an augmented conditionContext /// </summary> /// <param name="ics"></param> /// <returns></returns> protected override IStatement ConvertCondition(IConditionStatement ics) { if (CodeRecognizer.IsStochastic(context, ics.Condition)) { return(base.ConvertCondition(ics)); } // ics.Condition is not stochastic context.SetPrimaryOutput(ics); ConvertExpression(ics.Condition); ConditionBinding binding = new ConditionBinding(ics.Condition); int startIndex = conditionContext.Count; conditionContext.Add(binding); ConvertBlock(ics.Then); if (ics.Else != null) { conditionContext.RemoveRange(startIndex, conditionContext.Count - startIndex); binding = binding.FlipCondition(); conditionContext.Add(binding); ConvertBlock(ics.Else); } conditionContext.RemoveRange(startIndex, conditionContext.Count - startIndex); return(ics); }
public virtual IStatement TransformConditionStatement(IConditionStatement value) { value.Condition = this.TransformExpression(value.Condition); value.Then = (IBlockStatement)this.TransformStatement(value.Then); value.Else = (IBlockStatement)this.TransformStatement(value.Else); return value; }
public virtual void VisitConditionStatement(IConditionStatement value) { this.VisitExpression(value.Condition); this.VisitStatement(value.Then); this.VisitStatement(value.Else); }
private void WriteConditionStatement(IConditionStatement statement, IFormatter formatter) { this.WriteStatementSeparator(formatter); formatter.WriteKeyword("if"); formatter.Write(" "); if (statement.Condition is IBinaryExpression) this.WriteExpression(statement.Condition, formatter); else { formatter.Write("("); this.WriteExpression(statement.Condition, formatter); formatter.Write(")"); } formatter.Write(" {"); formatter.WriteLine(); formatter.WriteIndent(); if (statement.Then != null) this.WriteStatement(statement.Then, formatter); else formatter.WriteLine(); formatter.WriteOutdent(); formatter.Write("}"); if ((statement.Else != null) && (statement.Else.Statements.Count > 0)) { this.WritePendingOutdent(formatter); formatter.WriteLine(); formatter.WriteKeyword("else"); formatter.Write(" {"); formatter.WriteLine(); formatter.WriteIndent(); if (statement.Else != null) { this.WriteStatement(statement.Else, formatter); this.WritePendingOutdent(formatter); } else { formatter.WriteLine(); } formatter.WriteOutdent(); formatter.Write("}"); } }
protected IList <IStatement> Schedule(IList <IStatement> isc) { List <StatementBlock> blocks = new List <StatementBlock>(); StatementBlock currentBlock = new StraightLine(); Dictionary <NodeIndex, StatementBlock> blockOfNode = new Dictionary <NodeIndex, StatementBlock>(); int firstIterPostBlockCount = 0; IConditionStatement firstIterPostStatement = null; // must include back edges for computing InitializerSets DependencyGraph2 g = new DependencyGraph2(context, isc, DependencyGraph2.BackEdgeHandling.Include, delegate(IWhileStatement iws) { blocks.Add(currentBlock); currentBlock = new Loop(iws); }, delegate(IWhileStatement iws) { blocks.Add(currentBlock); currentBlock = new StraightLine(); }, delegate(IConditionStatement ics) { firstIterPostBlockCount++; firstIterPostStatement = ics; }, delegate(IConditionStatement ics) { firstIterPostBlockCount--; }, delegate(IStatement ist, int index) { if (firstIterPostBlockCount > 0) { ((Loop)currentBlock).firstIterPostBlock.Add(index); } currentBlock.indices.Add(index); blockOfNode[index] = currentBlock; }); var dependencyGraph = g.dependencyGraph; blocks.Add(currentBlock); Set <NodeIndex> usedNodes = Set <NodeIndex> .FromEnumerable(g.outputNodes); Set <NodeIndex> usedBySelf = new Set <NodeIndex>(); // loop blocks in reverse order for (int i = blocks.Count - 1; i >= 0; i--) { StatementBlock block = blocks[i]; if (block is Loop loop) { if (!pruneDeadCode) { usedNodes = CollectUses(dependencyGraph, block.indices); } else { usedBySelf.Clear(); block.indices = PruneDeadNodesCyclic(g, block.indices, usedNodes, usedBySelf, out List <int> tailStmts); // modifies usedNodes loop.tail = tailStmts; } RemoveSuffix(block.indices, loop.firstIterPostBlock); } else { // StraightLine if (pruneDeadCode) { block.indices = PruneDeadNodes(g, block.indices, usedNodes, usedBySelf); // modifies usedNodes } } AddLoopInitializers(block, usedNodes, blockOfNode, g); } IList <IStatement> sc = Builder.StmtCollection(); foreach (StatementBlock block in blocks) { if (block is Loop loop) { context.OpenStatement(loop.loopStatement); IWhileStatement ws = Builder.WhileStmt(loop.loopStatement); context.SetPrimaryOutput(ws); IList <IStatement> sc2 = ws.Body.Statements; foreach (NodeIndex i in loop.indices) { IStatement st = ConvertStatement(g.nodes[i]); sc2.Add(st); } context.CloseStatement(loop.loopStatement); context.InputAttributes.CopyObjectAttributesTo(loop.loopStatement, context.OutputAttributes, ws); sc.Add(ws); List <IStatement> initStmts = new List <IStatement>(); initStmts.AddRange(loop.initializers); if (loop.firstIterPostBlock.Count > 0) { var firstIterPostStatements = loop.firstIterPostBlock.Select(i => g.nodes[i]); var thenBlock = Builder.BlockStmt(); ConvertStatements(thenBlock.Statements, firstIterPostStatements); var firstIterPostStmt = Builder.CondStmt(firstIterPostStatement.Condition, thenBlock); context.OutputAttributes.Set(firstIterPostStmt, new FirstIterationPostProcessingBlock()); sc2.Add(firstIterPostStmt); loopMergingInfo.AddNode(firstIterPostStmt); } context.OutputAttributes.Remove <InitializerSet>(ws); context.OutputAttributes.Set(ws, new InitializerSet(initStmts)); if (loop.tail != null) { foreach (NodeIndex i in loop.tail) { IStatement st = g.nodes[i]; sc.Add(st); } } } else { foreach (NodeIndex i in block.indices) { IStatement st = ConvertStatement(g.nodes[i]); sc.Add(st); } } } return(sc); }