• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Tint Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/transform/for_loop_to_loop.h"
16 
17 #include "src/ast/break_statement.h"
18 #include "src/program_builder.h"
19 
20 TINT_INSTANTIATE_TYPEINFO(tint::transform::ForLoopToLoop);
21 
22 namespace tint {
23 namespace transform {
24 ForLoopToLoop::ForLoopToLoop() = default;
25 
26 ForLoopToLoop::~ForLoopToLoop() = default;
27 
Run(CloneContext & ctx,const DataMap &,DataMap &)28 void ForLoopToLoop::Run(CloneContext& ctx, const DataMap&, DataMap&) {
29   ctx.ReplaceAll(
30       [&](const ast::ForLoopStatement* for_loop) -> const ast::Statement* {
31         ast::StatementList stmts;
32         if (auto* cond = for_loop->condition) {
33           // !condition
34           auto* not_cond = ctx.dst->create<ast::UnaryOpExpression>(
35               ast::UnaryOp::kNot, ctx.Clone(cond));
36 
37           // { break; }
38           auto* break_body =
39               ctx.dst->Block(ctx.dst->create<ast::BreakStatement>());
40 
41           // if (!condition) { break; }
42           stmts.emplace_back(ctx.dst->If(not_cond, break_body));
43         }
44         for (auto* stmt : for_loop->body->statements) {
45           stmts.emplace_back(ctx.Clone(stmt));
46         }
47 
48         const ast::BlockStatement* continuing = nullptr;
49         if (auto* cont = for_loop->continuing) {
50           continuing = ctx.dst->Block(ctx.Clone(cont));
51         }
52 
53         auto* body = ctx.dst->Block(stmts);
54         auto* loop = ctx.dst->create<ast::LoopStatement>(body, continuing);
55 
56         if (auto* init = for_loop->initializer) {
57           return ctx.dst->Block(ctx.Clone(init), loop);
58         }
59 
60         return loop;
61       });
62 
63   ctx.Clone();
64 }
65 
66 }  // namespace transform
67 }  // namespace tint
68