cxx2flow 0.6.2

Convert your C/C++ code to control flow chart
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use std::{cell::RefCell, rc::Rc};

use crate::ast::{Ast, AstNode};
#[allow(unused_imports)]
use crate::dump::dump_node;
use crate::error::{Error, Result};
use tree_sitter::{Node, Parser, TreeCursor};

fn filter_ast<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
    if node.kind() == kind {
        return Some(node);
    }
    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            if let Some(v) = filter_ast(cursor.node(), kind) {
                return Some(v);
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    None
}

pub fn parse(
    content: &[u8],
    _file_name: &str,
    function_name: Option<String>,
) -> Result<Rc<RefCell<Ast>>> {
    let mut parser = Parser::new();
    let language = tree_sitter_cpp::language();
    parser.set_language(&language)?;
    let tree = parser
        .parse(content, None)
        .ok_or(Error::TreesitterParseFailed)?;
    let mut cursor = tree.walk();
    cursor.goto_first_child();
    let mut functions: Vec<Node> = Vec::new();
    loop {
        let node = cursor.node();
        let node = filter_ast(node, "function_definition");
        if let Some(node) = node {
            functions.push(node);
        }
        if !cursor.goto_next_sibling() {
            break;
        }
    }
    let target_function = function_name.unwrap_or_else(|| "main".to_string());
    for i in functions {
        cursor.reset(i);
        let stats = cursor
            .node()
            .child_by_field_name("body")
            .ok_or(Error::ChildNotFound)?;
        let node = cursor
            .node()
            .child_by_field_name("declarator")
            .ok_or(Error::DeclaratorNotFound)?;
        let func_name = filter_ast(node, "identifier");
        if func_name.is_none() {
            continue;
        }
        let func_name = func_name.unwrap().utf8_text(content)?;
        if func_name != target_function {
            continue;
        }
        let res = parse_stat(stats, content)?;
        remove_dummy(res.clone());
        return Ok(res);
    }
    Err(Error::FunctionNotFound {
        src: target_function.clone(),
        range: (0..target_function.len()).into(),
    })
}

fn remove_dummy(ast: Rc<RefCell<Ast>>) {
    match &mut ast.borrow_mut().node {
        AstNode::If {
            body, otherwise, ..
        } => {
            remove_dummy(body.clone());
            if let Some(otherwise) = otherwise {
                remove_dummy(otherwise.clone());
            }
        }
        AstNode::While { body, .. }
        | AstNode::DoWhile { body, .. }
        | AstNode::For { body, .. }
        | AstNode::Switch { body, .. } => {
            remove_dummy(body.clone());
        }
        AstNode::Compound(v) => {
            v.retain(|x| !matches!(x.borrow().node, AstNode::Dummy));
            v.iter().for_each(|x| {
                remove_dummy(x.clone());
            });
        }
        _ => {}
    }
}

fn parse_stat(stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    match stat.kind() {
        "compound_statement" => {
            let mut cursor = stat.walk();
            let mut vec = Vec::new();
            if !cursor.goto_first_child() {
                return Ok(Rc::new(RefCell::new(Ast::new(
                    AstNode::Compound(Vec::new()),
                    stat.byte_range(),
                    None,
                ))));
            }
            loop {
                let node = cursor.node();
                let ast = parse_stat(node, content)?;
                vec.push(ast);
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
            Ok(Rc::new(RefCell::new(Ast::new(
                AstNode::Compound(vec),
                stat.byte_range(),
                None,
            ))))
        }
        "labeled_statement" => {
            let mut label_vec = Vec::new();
            let mut cursor = stat.walk();
            loop {
                let node = cursor.node();
                let label_str = node
                    .child_by_field_name("label")
                    .ok_or(Error::ChildNotFound)?
                    .utf8_text(content)?;
                label_vec.push(label_str.to_owned());
                cursor.goto_first_child();
                while cursor.goto_next_sibling() {}
                if cursor.node().kind() != "labeled_statement" {
                    break;
                }
            }
            let ast = parse_stat(cursor.node(), content)?;
            ast.borrow_mut().label = Some(label_vec);
            Ok(ast)
        }
        _ => {
            let res = parse_single_stat(stat, content);
            match res {
                Ok(res) => Ok(res),
                Err(msg) => {
                    if !matches!(msg, Error::GarbageToken(_)) {
                        Err(msg)
                    } else {
                        Ok(Rc::new(RefCell::new(Ast::new(
                            AstNode::Dummy,
                            stat.byte_range(),
                            None,
                        ))))
                    }
                }
            }
        }
    }
}

fn parse_single_stat(stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    match stat.kind() {
        "continue_statement" => Ok(Rc::new(RefCell::new(Ast::new(
            AstNode::Continue("continue".to_string()),
            stat.byte_range(),
            None,
        )))),
        "break_statement" => Ok(Rc::new(RefCell::new(Ast::new(
            AstNode::Break("break".to_string()),
            stat.byte_range(),
            None,
        )))),
        "return_statement" => {
            let str = stat.utf8_text(content)?;
            Ok(Rc::new(RefCell::new(Ast::new(
                AstNode::Return(String::from(str)),
                stat.byte_range(),
                None,
            ))))
        }
        "if_statement" => parse_if_stat(stat, content),
        "while_statement" => parse_while_stat(stat, content),
        "do_statement" => parse_do_while_stat(stat, content),
        "for_statement" => parse_for_stat(stat, content),
        "for_range_loop" => parse_range_for_stat(stat, content),
        "switch_statement" => parse_switch_stat(stat, content),
        "goto_statement" => parse_goto_stat(stat, content),
        "expression_statement" | "declaration" => {
            let str = stat.utf8_text(content)?;
            Ok(Rc::new(RefCell::new(Ast::new(
                AstNode::Stat(String::from(str)),
                stat.byte_range(),
                None,
            ))))
        }
        // ignore all unrecognized token
        c => Err(Error::GarbageToken(c)),
    }
}

fn parse_if_stat(if_stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    let condition = if_stat
        .child_by_field_name("condition")
        .ok_or(Error::ChildNotFound)?;
    let blk1 = if_stat.child_by_field_name("consequence");
    let blk2 = if_stat.child_by_field_name("alternative");
    let cond_str = condition.utf8_text(content)?;
    let body = parse_stat(blk1.ok_or(Error::ChildNotFound)?, content)?;

    let otherwise = if let Some(blk2) = blk2 {
        let cnt = blk2.child_count();
        Some(parse_stat(
            blk2.child(cnt - 1).ok_or(Error::ChildNotFound)?,
            content,
        )?)
    } else {
        None
    };

    let res = Rc::new(RefCell::new(Ast::new(
        AstNode::If {
            cond: String::from(cond_str),
            body,
            otherwise,
        },
        if_stat.byte_range(),
        None,
    )));
    Ok(res)
}

fn parse_while_stat(while_stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    let condition = while_stat
        .child_by_field_name("condition")
        .ok_or(Error::ChildNotFound)?;
    let body = while_stat.child_by_field_name("body");
    let cond_str = condition.utf8_text(content)?;
    let body = parse_stat(body.ok_or(Error::ChildNotFound)?, content)?;

    let res = Rc::new(RefCell::new(Ast::new(
        AstNode::While {
            cond: String::from(cond_str),
            body,
        },
        while_stat.byte_range(),
        None,
    )));
    Ok(res)
}

/// return first child, or return the case label
fn get_case_child_and_label<'a>(
    mut case_stat: tree_sitter::TreeCursor<'a>,
    content: &[u8],
) -> Result<(Option<TreeCursor<'a>>, String)> {
    // dump_node(&case_stat.node(), None);
    let label = {
        let tmp = if case_stat
            .node()
            .child(0)
            .ok_or(Error::ChildNotFound)?
            .kind()
            == "case"
        {
            case_stat
                .node()
                .child(1)
                .ok_or(Error::ChildNotFound)?
                .utf8_text(content)?
        } else {
            case_stat
                .node()
                .child(0)
                .ok_or(Error::ChildNotFound)?
                .utf8_text(content)?
        };
        tmp.into()
    };
    case_stat.goto_first_child();
    if case_stat.node().kind() == "case" {
        // case lit :
        case_stat.goto_next_sibling();
        case_stat.goto_next_sibling();
    } else if case_stat.node().kind() == "default" {
        // default :
        case_stat.goto_next_sibling();
    }
    while [":", "comment"].contains(&case_stat.node().kind()) {
        if !case_stat.goto_next_sibling() {
            return Ok((None, label));
        }
    }
    // dump_node(&case_stat.node(), None);
    Ok((Some(case_stat), label))
}

fn parse_switch_stat(switch_stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    let condition = switch_stat
        .child_by_field_name("condition")
        .ok_or(Error::ChildNotFound)?;
    let body = switch_stat
        .child_by_field_name("body")
        .ok_or(Error::ChildNotFound)?;
    let cond_str = condition.utf8_text(content)?;
    let mut stats = Vec::new();
    let mut labels = Vec::new();
    let mut cases = Vec::new();
    let mut cursor = body.walk();
    cursor.goto_first_child(); // brace
    cursor.goto_next_sibling(); // case statement
                                // dbg!(cursor.node());
    loop {
        let (child, label) = get_case_child_and_label(cursor.clone(), content)?;
        labels.push(label.clone());
        cases.push(label);
        if let Some(child) = child {
            let mut cursor = child;
            let first_idx = stats.len();
            loop {
                let stat = parse_stat(cursor.node(), content)?;
                stats.push(stat);
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
            stats[first_idx].borrow_mut().label = Some(labels.clone());
            labels.clear();
        }
        if !cursor.goto_next_sibling() {
            break;
        }
        if cursor.node().kind() != "case_statement" {
            break;
        }
    }
    let inner = Rc::new(RefCell::new(Ast::new(
        AstNode::Compound(stats),
        switch_stat.byte_range(),
        None,
    )));
    let res = Rc::new(RefCell::new(Ast::new(
        AstNode::Switch {
            cond: String::from(cond_str),
            cases,
            body: inner,
        },
        switch_stat.byte_range(),
        None,
    )));
    Ok(res)
}

fn parse_goto_stat(goto_stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    let label_str = goto_stat
        .child_by_field_name("label")
        .ok_or(Error::ChildNotFound)?
        .utf8_text(content)?;
    Ok(Rc::new(RefCell::new(Ast::new(
        AstNode::Goto(label_str.to_owned()),
        goto_stat.byte_range(),
        None,
    ))))
}

fn parse_do_while_stat(do_while_stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    let condition = do_while_stat
        .child_by_field_name("condition")
        .ok_or(Error::ChildNotFound)?;
    let body = do_while_stat.child_by_field_name("body");
    let cond_str = condition.utf8_text(content)?;
    let body = parse_stat(body.ok_or(Error::ChildNotFound)?, content)?;
    let res = Rc::new(RefCell::new(Ast::new(
        AstNode::DoWhile {
            cond: String::from(cond_str),
            body,
        },
        do_while_stat.byte_range(),
        None,
    )));

    Ok(res)
}

fn parse_for_stat(for_stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    let mut cursor = for_stat.walk();
    let init = for_stat.child_by_field_name("initializer");
    let cond = for_stat.child_by_field_name("condition");
    let update = for_stat.child_by_field_name("update");
    let mut init_str: String = String::new();
    let mut cond_str: String = String::from("true");
    let mut update_str: String = String::new();
    if let Some(init) = init {
        let init = init.utf8_text(content)?;
        init_str = String::from(init);
    }
    if let Some(cond) = cond {
        let cond = cond.utf8_text(content)?;
        cond_str = String::from(cond);
    }
    if let Some(update) = update {
        let update = update.utf8_text(content)?;
        update_str = String::from(update);
    }
    cursor.goto_first_child();
    while cursor.goto_next_sibling() {}
    let body = parse_stat(cursor.node(), content)?;
    let res = Rc::new(RefCell::new(Ast::new(
        AstNode::For {
            init: init_str,
            cond: cond_str,
            upd: update_str,
            body,
        },
        for_stat.byte_range(),
        None,
    )));
    Ok(res)
}

fn parse_range_for_stat(range_for_stat: Node, content: &[u8]) -> Result<Rc<RefCell<Ast>>> {
    let ty = range_for_stat
        .child_by_field_name("type")
        .ok_or(Error::ChildNotFound)?;
    let declarator = range_for_stat
        .child_by_field_name("declarator")
        .ok_or(Error::ChildNotFound)?;
    let range = range_for_stat
        .child_by_field_name("right")
        .ok_or(Error::ChildNotFound)?;
    let body = range_for_stat
        .child_by_field_name("body")
        .ok_or(Error::ChildNotFound)?;
    let body = parse_stat(body, content)?;
    let type_text = ty.utf8_text(content)?;
    let init_text = declarator.utf8_text(content)?;
    let range_text = range.utf8_text(content)?;
    let real_init_text = format!("{init_text}_iter = {range_text}.begin()");
    let real_cond_text = format!("{init_text}_iter != {range_text}.end()");
    let real_update_text = format!("++{init_text}_iter");
    let res = Rc::new(RefCell::new(Ast::new(
        AstNode::For {
            init: real_init_text,
            cond: real_cond_text,
            upd: real_update_text,
            body: Rc::new(RefCell::new(Ast::new(
                AstNode::Compound(vec![
                    Rc::new(RefCell::new(Ast::new(
                        AstNode::Stat(format!("{type_text} {init_text} = *{init_text}_iter")),
                        range_for_stat.byte_range(),
                        None,
                    ))),
                    body,
                ]),
                range_for_stat.byte_range(),
                None,
            ))),
        },
        range_for_stat.byte_range(),
        None,
    )));
    Ok(res)
}