public override void VisitWhileStatement(IWhileStatement rsLoop, IList <IStatement> body) { if (_marker.HandlingNode == rsLoop && _marker.Case == CompletionCase.EmptyCompletionBefore) { body.Add(EmptyCompletionExpression); } var loop = new WhileLoop { Condition = _exprVisitor.ToLoopHeaderExpression(rsLoop.Condition, body) }; body.Add(loop); if (_marker.HandlingNode == rsLoop && _marker.Case == CompletionCase.InBody) { loop.Body.Add(EmptyCompletionExpression); } rsLoop.Body.Accept(this, loop.Body); if (_marker.HandlingNode == rsLoop && _marker.Case == CompletionCase.EmptyCompletionAfter) { body.Add(EmptyCompletionExpression); } }
public override void VisitWhileStatement <TExpression, TStatement>(IWhileStatement <TExpression, TStatement> whileStatement) { Value = new Statement() { WhileStatement = new WhileStatementFactory(whileStatement).Value }; }
protected override void DoConvertMethodBody(IList <IStatement> outputs, IList <IStatement> inputs) { Dictionary <IStatement, IStatement> replacements = new Dictionary <IStatement, IStatement>(ReferenceEqualityComparer <IStatement> .Instance); ProcessStatements(outputs, outputs, inputs, replacements); // update all dependencies foreach (IStatement ist in outputs) { if (ist is IWhileStatement) { IWhileStatement iws = (IWhileStatement)ist; foreach (IStatement st in iws.Body.Statements) { DependencyInformation di2 = context.OutputAttributes.Get <DependencyInformation>(st); if (di2 != null) { di2.Replace(replacements); } } } else { DependencyInformation di = context.OutputAttributes.Get <DependencyInformation>(ist); if (di != null) { di.Replace(replacements); } } } }
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); } }
private void AnalyzeWhileStatement(IWhileStatement source, int idx) { using (m_currentLocationStack.AutoPush("__while__" + idx.ToString())) { AnalyzeExpression(source.Expression, idx); AnalyzeStatement(source.Statement, idx); } }
public static void VisitWhileStatementChildren <TExpression, TStatement>( IWhileStatement <TExpression, TStatement> whileStatement, IGenericStatementVisitor visitor) where TExpression : IExpression where TStatement : IStatement { VisitIfNotNull(whileStatement.Statement, visitor); }
public override void VisitWhileStatement <TExpression, TStatement>(IWhileStatement <TExpression, TStatement> whileStatement) { Steps.Add(new WriteWhileKeyword()); Steps.Add(new WriteWhitespace()); Steps.Add(new WriteStartParenthesis()); Steps.Add(new WriteExpression <TExpression>(whileStatement.Condition)); Steps.Add(new WriteEndParenthesis()); Steps.AddIndentedStatementSteps(whileStatement.Statement); }
public void Generate(IWhileStatement statement) { Spit("while("); Generate(statement.condition); Spit("){"); foreach (var st in statement.statements.EmptyIfNull()) { Generate(st); } Spit("}"); }
public override bool Visit(IWhileStatement whileStatement, IStatement context) { _stack.Push(whileStatement); try { return(base.Visit(whileStatement, context)); } finally { _stack.Pop(); } }
protected override IStatement ConvertWhile(IWhileStatement iws) { IStatement st = base.ConvertWhile(iws); InitializerSet initSet = context.InputAttributes.Get <InitializerSet>(iws); if (initSet != null) { // initializers occur in the loop, so all replacements should already be known. initSet.Replace(replacements); } return(st); }
protected override IStatement DoConvertStatement(IStatement ist) { if (ist is IWhileStatement) { IWhileStatement iws = (IWhileStatement)ist; if (whileCount == 0) { replacements.Clear(); } whileCount++; IStatement convertedSt = ConvertWhile(iws); whileCount--; if (replacements.Count > 0) { InitializerSet initializerSet = context.InputAttributes.Get <InitializerSet>(iws); if (initializerSet != null) { initializerSet.Replace(replacements); } } return(convertedSt); } else if (isInnerStatement) { return(ist); } else if (context.InputAttributes.Has <FirstIterationPostProcessingBlock>(ist)) { return(base.DoConvertStatement(ist)); } else if (!previousStatements.Contains(ist)) { previousStatements.Add(ist); return(ist); } else { this.ShallowCopy = true; isInnerStatement = true; IStatement convertedSt = base.DoConvertStatement(ist); isInnerStatement = false; this.ShallowCopy = false; AddClone(ist, convertedSt); loopMergingInfo.AddEquivalentStatement(convertedSt, loopMergingInfo.GetIndexOf(ist)); return(convertedSt); } }
public override bool Equals(object obj) { if (this == obj) { return(true); } IWhileStatement statement = obj as IWhileStatement; if (statement == null) { return(false); } return (this.Body.Equals(statement.Body) && this.Condition.Equals(statement.Condition)); }
private static void WriteWhile(LanguageWriter w, IWhileStatement state) { w.WriteKeyword("while"); w.Write(" "); w.Write("("); if (state.Condition != null) { w.SkipWriteLine = true; ExpressionWriter.WriteExpression(w, state.Condition, false); w.SkipWriteLine = false; } w.Write(") {"); w.WriteLine(); w.WriteIndent(); if (state.Body != null) { WriteStatement(w, state.Body); } w.WriteOutdent(); w.Write("}"); w.WriteLine(); }
protected CognitiveComplexityHintBase(ITreeNode node, DocumentOffset offset, int value) { _node = node; _offset = offset; Value = value; Description = node switch { IWhileStatement _ => "While-Statement (increases nesting)", ISwitchStatement _ => "Switch-Statement (increases nesting)", IDoStatement _ => "Do-While-Statement (increases nesting)", IIfStatement _ => "If-Statement (increases nesting)", IForStatement _ => "For-Statement (increases nesting)", IForeachStatement _ => "Foreach-Statement (increases nesting)", ICatchClause _ => "Catch-Clause (increases nesting)", IGotoStatement _ => "Goto-Statement", IBreakStatement _ => "Break-Statement", IConditionalOrExpression _ => "First/alternating conditional Expression", IConditionalAndExpression _ => "First/alternating conditional Expression", ICSharpStatement _ => "If-Statement (increases nesting)", ICSharpExpression _ => "Recursive Call", _ => throw new NotSupportedException(node.GetType().FullName) }; }
private List <IStatement> Schedule(DependencyGraph g, IList <IStatement> stmts, bool createFirstIterPostBlocks) { List <IStatement> output = new List <IStatement>(); List <StatementBlock> blocks = new List <StatementBlock>(); List <NodeIndex> currentBlock = null; DirectedGraphFilter <NodeIndex, EdgeIndex> graph2 = new DirectedGraphFilter <NodeIndex, EdgeIndex>(g.dependencyGraph, edge => !g.isDeleted[edge]); StrongComponents2 <NodeIndex> scc = new StrongComponents2 <NodeIndex>(graph2.SourcesOf, graph2); scc.AddNode += delegate(NodeIndex node) { currentBlock.Add(node); }; scc.BeginComponent += delegate() { currentBlock = new List <int>(); }; scc.EndComponent += delegate() { bool isCyclic = false; if (currentBlock.Count == 1) { NodeIndex node = currentBlock[0]; foreach (NodeIndex source in graph2.SourcesOf(node)) { if (source == node) { isCyclic = true; break; } } } else { isCyclic = true; } if (isCyclic) { blocks.Add(new Loop() { indices = currentBlock }); } else { blocks.Add(new StraightLine() { indices = currentBlock }); } }; scc.SearchFrom(graph2.Nodes); //scc.SearchFrom(g.outputNodes); bool check = false; if (check) { // check that there are no edges from a later component to an earlier component Set <NodeIndex> earlierNodes = new Set <int>(); foreach (StatementBlock block in blocks) { earlierNodes.AddRange(block.indices); foreach (NodeIndex node in block.indices) { foreach (NodeIndex source in graph2.SourcesOf(node)) { if (!earlierNodes.Contains(source)) { Console.WriteLine(g.NodeToString(node) + Environment.NewLine + " depends on later node " + g.NodeToString(source)); Error("Internal error: Strong components are not ordered properly"); } } } } } Set <NodeIndex> nodesToMove = new Set <NodeIndex>(); Dictionary <Loop, IBlockStatement> firstIterPostprocessing = null; if (createFirstIterPostBlocks) { firstIterPostprocessing = GetFirstIterPostprocessing(blocks, graph2, stmts, nodesToMove); } IVariableDeclaration iteration = Builder.VarDecl("iteration", typeof(int)); IndexedProperty <NodeIndex, bool> isUniform = graph2.CreateNodeData <bool>(true); foreach (StatementBlock block in blocks) { if (block is Loop) { foreach (NodeIndex i in block.indices) { isUniform[i] = false; } IWhileStatement ws = Builder.WhileStmt(Builder.LiteralExpr(true)); IList <IStatement> whileBody = ws.Body.Statements; if (ContainsIterationStatement(stmts, block.indices)) { List <IStatement> nodes = new List <IStatement>(); foreach (NodeIndex i in block.indices) { IStatement ist = stmts[i]; if (!context.InputAttributes.Has <IterationStatement>(ist)) { nodes.Add(ist); } } // build a new dependency graph with the dummy iteration statement removed DependencyGraph g2 = new DependencyGraph(context, nodes, ignoreMissingNodes: true, ignoreRequirements: true); List <IStatement> sc3 = Schedule(g2, nodes, false); if (sc3.Count == 1 && sc3[0] is IWhileStatement) { ws = (IWhileStatement)sc3[0]; } else { // The statements in the outer loop are not strongly connected. // Since we want the next transform to only process strong components, // we mark the outer while loop as DoNotSchedule, leaving only the // inner while loops to be scheduled. // add all statements in sc3 to whileBody, but remove while loops around a single statement. foreach (IStatement ist in sc3) { if (ist is IWhileStatement) { IWhileStatement iws2 = (IWhileStatement)ist; if (iws2.Body.Statements.Count == 1) { whileBody.AddRange(iws2.Body.Statements); continue; } } whileBody.Add(ist); } context.OutputAttributes.Set(ws, new DoNotSchedule()); } } else // !ContainsIterationStatement { foreach (NodeIndex i in block.indices) { IStatement st = stmts[i]; whileBody.Add(st); DependencyInformation di = context.InputAttributes.Get <DependencyInformation>(st); di.AddClones(clonesOfStatement); } RegisterUnchangedStatements(whileBody); } Loop loop = (Loop)block; if (firstIterPostprocessing != null && firstIterPostprocessing.ContainsKey(loop)) { var thenBlock = firstIterPostprocessing[loop]; var iterIsZero = Builder.BinaryExpr(BinaryOperator.ValueEquality, Builder.VarRefExpr(iteration), Builder.LiteralExpr(0)); var firstIterPostStmt = Builder.CondStmt(iterIsZero, thenBlock); context.OutputAttributes.Set(firstIterPostStmt, new FirstIterationPostProcessingBlock()); whileBody.Add(firstIterPostStmt); } output.Add(ws); } else { // not cyclic foreach (NodeIndex i in block.indices) { IStatement st = stmts[i]; if (!nodesToMove.Contains(i)) { output.Add(st); DependencyInformation di = context.InputAttributes.Get <DependencyInformation>(st); di.AddClones(clonesOfStatement); } isUniform[i] = g.IsUniform(i, source => !isUniform[source]); if (isUniform[i] != g.isUniform[i]) { Assert.IsTrue(isUniform[i]); g.isUniform[i] = isUniform[i]; DependencyInformation di = context.InputAttributes.Get <DependencyInformation>(st); di.IsUniform = isUniform[i]; } // mark sources of output statements (for SchedulingTransform) if (g.outputNodes.Contains(i)) { foreach (NodeIndex source in graph2.SourcesOf(i)) { IStatement sourceSt = stmts[source]; if (!context.InputAttributes.Has <OutputSource>(sourceSt)) { context.OutputAttributes.Set(sourceSt, new OutputSource()); } } } } } } return(output); }
public abstract IStatement Transform(IWhileStatement statement);
public abstract void Translate(IWhileStatement statement);
void IStatementVisitor.Visit(IWhileStatement statement) { this.Translate(statement); }
protected override IStatement ConvertWhile(IWhileStatement iws) { bool wasInWhileLoop = this.inWhileLoop; if (!wasInWhileLoop) { // collect all statements in the body of this loop (and any nested loops). DeadCodeTransform.ForEachStatement(iws.Body.Statements, _ => { }, _ => { }, _ => { }, _ => { }, ist => { visitedStatements.Add(ist); }); // collect all IncrementStatement attributes in the body of this loop (and any nested loops). DeadCodeTransform.ForEachStatement(iws.Body.Statements, _ => { }, _ => { }, _ => { }, _ => { }, ist => { var incrementStatement = context.GetAttribute <IncrementStatement>(ist); if (incrementStatement != null) { DependencyInformation di = context.GetAttribute <DependencyInformation>(ist); if (di != null && !di.GetDependenciesOfType(DependencyType.Cancels).All(visitedStatements.Contains)) { // Remove increment statements whose Cancels input is not available, implying that there is no purpose in carrying out the increment. // This happens because IterationTransform ignores Cancels edges. replacements[ist] = null; } else { incrementStatements.Add(incrementStatement); } } }); ancestorIndexOfWhile = context.Depth - 1; } this.inWhileLoop = true; var ws = base.ConvertWhile(iws); this.inWhileLoop = wasInWhileLoop; if (!wasInWhileLoop) { incrementStatements.Clear(); } return(ws); }
private void WriteWhileStatement(IWhileStatement statement, IFormatter formatter) { this.WriteStatementSeparator(formatter); formatter.WriteKeyword("while"); formatter.Write(" "); formatter.Write("("); if (statement.Condition != null) { this.WriteExpression(statement.Condition, formatter); } else formatter.WriteLiteral("true"); formatter.Write(")"); formatter.Write(" {"); formatter.WriteLine(); formatter.WriteIndent(); if (statement.Body != null) { this.WriteStatement(statement.Body, formatter); } formatter.WriteLine(); formatter.WriteOutdent(); formatter.Write("}"); }
public override void VisitWhileStatement(IWhileStatement whileStatement, IHighlightingConsumer consumer) { VisitLoop(whileStatement, consumer); }
public VWhileStatement(IWhileStatement whileStatement) : base("выполнять пока", whileStatement) { BackColor = ColorSettings.Get("WhileStatement"); }
TransformationImpact IStatementVisitor <TransformationImpact> .Visit(IWhileStatement statement) { return(CalculateRefactorImpact(statement)); }
public bool Visit(IWhileStatement whileStatement, TContext context) { return(IsBrokeFull(whileStatement, context)); }
public virtual void VisitWhileStatement(IWhileStatement value) { this.VisitExpression(value.Condition); this.VisitStatement(value.Body); }
public abstract TransformationImpact CalculateRefactorImpact(IWhileStatement statement);
public Loop(IWhileStatement loopStatement) { this.loopStatement = loopStatement; }
public TransformationKind Visit(IWhileStatement whileStatement, ITransformationContext context) { throw new NotImplementedException(); }
void ProcessStatements(IList <IStatement> outputs, IList <IStatement> outputDecls, IList <IStatement> inputs, Dictionary <IStatement, IStatement> replacements) { for (int i = 0; i < inputs.Count; i++) { IStatement ist = inputs[i]; if (ist is IWhileStatement) { IWhileStatement iws = (IWhileStatement)ist; IWhileStatement ws = Builder.WhileStmt(iws); bool doNotSchedule = context.InputAttributes.Has <DoNotSchedule>(iws); if (doNotSchedule) { // iws may contain nested while loops // TODO: make sure the new decls go in the right place ProcessStatements(ws.Body.Statements, outputDecls, iws.Body.Statements, replacements); } else { IReadOnlyList <IStatement> inputStmts = (IReadOnlyList <IStatement>)iws.Body.Statements; IStatement firstIterPostBlock = ForwardBackwardTransform.ExtractFirstIterationPostProcessingBlock(context, ref inputStmts); DependencyGraph g = new DependencyGraph(context, inputStmts, ignoreMissingNodes: true, ignoreRequirements: true); // look for cycles of initialized nodes and insert clones as needed Set <NodeIndex> nodesToClone = GetNodesToClone(g, g.dependencyGraph.Nodes); for (int node = 0; node < inputStmts.Count; node++) { IStatement st = inputStmts[node]; if (nodesToClone.Contains(node)) { cloneDecls.Clear(); cloneUpdates.Clear(); containers.Clear(); IStatement newStmt = ConvertStatement(st); IStatement declStmt = cloneDecls[0]; IStatement setToStmt = cloneUpdates[0]; outputDecls.AddRange(cloneDecls); DependencyInformation diNew = (DependencyInformation)context.InputAttributes.Get <DependencyInformation>(newStmt).Clone(); context.OutputAttributes.Remove <DependencyInformation>(newStmt); context.OutputAttributes.Set(newStmt, diNew); DependencyInformation diSet = new DependencyInformation(); diSet.Add(DependencyType.Dependency | DependencyType.Requirement, newStmt); context.OutputAttributes.Set(setToStmt, diSet); DependencyInformation diDecl = new DependencyInformation(); context.OutputAttributes.Set(declStmt, diDecl); foreach (IStatement writer in diNew.Overwrites) { diDecl.Add(DependencyType.Dependency, writer); diSet.Add(DependencyType.Overwrite, writer); } diNew.Remove(DependencyType.Overwrite); diNew.Add(DependencyType.Declaration | DependencyType.Dependency | DependencyType.Overwrite, declStmt); if (loopMergingInfo != null) { // update loopMergingInfo with the new statement int oldNode = loopMergingInfo.GetIndexOf(st); int newNode = loopMergingInfo.AddNode(newStmt); loopMergingInfo.InheritSourceConflicts(newNode, oldNode); int setToNode = loopMergingInfo.AddNode(setToStmt); loopMergingInfo.InheritTargetConflicts(setToNode, oldNode); int declNode = loopMergingInfo.AddNode(declStmt); } replacements[st] = setToStmt; context.InputAttributes.CopyObjectAttributesTo <InitialiseBackward>(st, context.OutputAttributes, setToStmt); st = newStmt; ws.Body.Statements.AddRange(cloneUpdates); } else { RegisterUnchangedStatement(st); } ws.Body.Statements.Add(st); } if (firstIterPostBlock != null) { ws.Body.Statements.Add(firstIterPostBlock); } } context.InputAttributes.CopyObjectAttributesTo(iws, context.OutputAttributes, ws); ist = ws; } else { RegisterUnchangedStatement(ist); } outputs.Add(ist); } }
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); }
public virtual void VisitWhileStatement(IWhileStatement value) { VisitExpression(value.Condition); VisitStatement(value.Body); }
public virtual void VisitWhileStatement <TExpression, TStatement>(IWhileStatement <TExpression, TStatement> whileStatement) where TExpression : IExpression where TStatement : IStatement { Visit(whileStatement); }
public virtual IStatement TransformWhileStatement(IWhileStatement value) { value.Condition = this.TransformExpression(value.Condition); value.Body = (IBlockStatement)this.TransformStatement(value.Body); return value; }