Debian Codegraph @

example/to-while

raw
1 #!/usr/bin/env node
2
3 // This script converts for and do-while loops into equivalent while loops.
4 // Note that for-in statements are left unmodified, as they do not have a
5 // simple analogy to while loops. Also note that labeled continue statements
6 // are not correctly handled at this point, and will trigger an assertion
7 // failure if encountered.
8
9 var assert = require("assert");
10 var recast = require("recast");
11 var types = recast.types;
12 var n = types.namedTypes;
13 var b = types.builders;
14
15 recast.run(function(ast, callback) {
16 recast.visit(ast, {
17 visitForStatement: function(path) {
18 var fst = path.node;
19
20 path.replace(
21 fst.init,
22 b.whileStatement(
23 fst.test,
24 insertBeforeLoopback(fst, fst.update)
25 )
26 );
27
28 this.traverse(path);
29 },
30
31 visitDoWhileStatement: function(path) {
32 var dwst = path.node;
33 return b.whileStatement(
34 b.literal(true),
35 insertBeforeLoopback(
36 dwst,
37 b.ifStatement(
38 dwst.test,
39 b.breakStatement()
40 )
41 )
42 );
43 }
44 });
45
46 callback(ast);
47 });
48
49 function insertBeforeLoopback(loop, toInsert) {
50 var body = loop.body;
51
52 if (!n.Statement.check(toInsert)) {
53 toInsert = b.expressionStatement(toInsert);
54 }
55
56 if (n.BlockStatement.check(body)) {
57 body.body.push(toInsert);
58 } else {
59 body = b.blockStatement([body, toInsert]);
60 loop.body = body;
61 }
62
63 recast.visit(body, {
64 visitContinueStatement: function(path) {
65 var cst = path.node;
66
67 assert.equal(
68 cst.label, null,
69 "Labeled continue statements are not yet supported."
70 );
71
72 path.replace(toInsert, path.node);
73 return false;
74 },
75
76 // Do not descend into nested loops.
77 visitWhileStatement: function() {},
78 visitForStatement: function() {},
79 visitForInStatement: function() {},
80 visitDoWhileStatement: function() {}
81 });
82
83 return body;
84 }