cyagen 0.1.11

Text file generator based on C file and templates
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use super::parser::Parser;

use anyhow::{Context, Result};
use chrono::Utc;
use regex::Regex;
use serde_json;
use std::fs;

use tera;
use uuid::Uuid;

const NAMESPACE_OID: Uuid = Uuid::from_u128(0x6ba7b812_9dad_11d1_80b4_00c04fd430c8);

fn generate_uuid(
    value: &tera::Value,
    _: &std::collections::HashMap<String, tera::Value>,
) -> tera::Result<tera::Value> {
    let uuid: Uuid = match value {
        tera::Value::String(s) => Uuid::new_v5(&NAMESPACE_OID, s.as_bytes()),
        _ => return Err(tera::Error::msg("Invalid value")),
    };
    Ok(tera::to_value(uuid.hyphenated().to_string()).unwrap())
}

/// Function to generate UUID
pub fn generate_using_tera<'a>(parser: &'a Parser, template: &'a str) -> String {
    let mut tera = tera::Tera::default();

    // register filter function
    tera.register_filter("generateUUID", generate_uuid);

    // prepare context from parser
    let json_data: tera::Value = serde_json::to_value(&parser).unwrap();
    let mut context = tera::Context::new();
    for (key, value) in json_data.as_object().unwrap() {
        context.insert(key, value);
    }

    // render template
    let result = tera.render_str(&template, &context);
    match result {
        Ok(value) => value,
        Err(error) => panic!("Error: {}", error),
    }
}

pub fn generate_json<'a>(parser: &'a Parser, filepath: &'a String) -> Result<()> {
    let file = fs::File::create(filepath)
        .with_context(|| format!("failed to create file `{}`", filepath))?;
    serde_json::to_writer(file, parser)?;
    Ok(())
}

pub fn merge_with_manual_sections(rendered: &str, old_gen: &str) -> String {
    let regex = Regex::new(r"(?s)MANUAL SECTION: ([a-f0-9-]+).*?MANUAL SECTION END").unwrap();
    let merged = regex.replace_all(&rendered, |captures: &regex::Captures<'_>| {
        let uuid = &captures[1];
        let manual_content = Regex::new(&format!(
            "(?s)MANUAL SECTION: {}.*?MANUAL SECTION END",
            uuid
        ))
        .unwrap();
        manual_content
            .find(old_gen)
            .map_or(captures[0].to_string(), |m| m.as_str().to_string())
    });

    merged.into_owned()
}

/// DUE-TO-BACKWARD-COMPATIBILITY
/// generate document based on parsing result and template data
///
/// # Available tags in template file
/// - **@sourcename@** : it is given as an argument from command line
/// - **@date@** : generated date
/// - **@incs@** : the list of inclusion statement such as `#include <stdio.h>`
///     - **@captured@** : the captured raw string
/// - **@end-incs@** : the end of **incs** block
/// - **@static-vars@** or **@static-global-vars@** or **@static-local-vars@**: the list of **static** variables
///     - **@captured@** : the captured raw string
///     - **@name@** : variable name
///     - **@name-expr@** : variable name including brackets when array data
///     - **@dtype@** : variable data type
///     - **@func-name@** : function name only for **static-local-vars**
/// - **@end-static-vars@** or **@end-static-global-vars@** or **@end-static-local-vars@**: the end of **static-vars** bolck
/// - **@fncs@** or **@fncs0@** : the list of all the functions
///     - **@captured@** : the captured raw string
///     - **@name@** : the function name
///     - **@rtype@** : the return data type of the function
///     - **@args@** : the list of arguments with data types
///     - **@atypes@** : the list of only arguments' data types
/// - **@end-fncs@** or **@end-fncs0@** : the end of **fncs** or **fncs0** block
/// - **@ncls@** or **@ncls-once@** : the list of nested calls, no duplicate callee with **ncls-once**
///     - **@callee.name@** : the function name of callee
///     - **@callee.rtype@** : the return type of callee
///     - **@callee.rtype.change(\<from\>=\<to\>)@** : to change return data type during generation
///     - **@callee.rtype.remove(\<text\>)@** : \<text\> to be removed when `void`
///     - **@callee.rtype.remove0(\<text\>)@** : \<text\> to be removed when `void`
///     - **@callee.args@** : the argument list string
///     - **@callee.args.remove(\<text\>)@** : \<text\> to be removed when `void`
///     - **@callee.atypes@** : only arguments' data types
///     - **@caller.name@** : the function name of caller
///     - **@caller.rtype@** : the return type of caller
///     - **@caller.args@** : the argument list string
///     - **@caller.atypes@** : only arguments' data types
/// - **@end-ncls@** or **@end-ncls-once@** : the end of **ncls** or **ncls-once** block
///
/// # Example
///
/// ```
/// let sourcename = "source";
/// let code = "\
/// #include <stdio.h>
/// static int var = 1;
/// static int func1(void)
/// {
///     return 0;
/// }
/// int func2(char c)
/// {
///     return func1();
/// }
/// ";
/// let temp = "\
/// // include
/// @incs@@captured@
/// @end-incs@
/// // local variables
/// @local-vars@@dtype@ @name@;
/// @end-local-vars@
/// // functions
/// @fncs@@rtype@ @name@(@args@);
/// @end-fncs@
/// ";
/// let parser = cyagen::Parser::parse(code);
/// let gen = cyagen::generate(&parser, temp, sourcename);
/// ```
pub fn generate<'a>(parser: &'a Parser, template: &'a str, sourcename: &'a str) -> String {
    let mut output = String::from(template);
    if template.contains("@incs@") {
        let re = Regex::new(r"@incs@(?P<fmt>[\S\s]*)@end-incs@").unwrap();
        for cap in re.captures_iter(template) {
            let mut tmpstr = String::new();
            for entry in &parser.incs {
                let fmtstr = cap
                    .name("fmt")
                    .unwrap()
                    .as_str()
                    .replace("@captured@", &entry.captured);
                tmpstr.push_str(&fmtstr);
            }
            output = re.replace(&output, tmpstr.as_str()).into_owned();
        }
    }
    if template.contains("@static-vars@") {
        let re = Regex::new(r"@static-vars@(?P<fmt>[\S\s]*)@end-static-vars@").unwrap();
        for cap in re.captures_iter(template) {
            let mut tmpstr = String::new();
            for entry in &parser.static_vars {
                let fmtstr = cap
                    .name("fmt")
                    .unwrap()
                    .as_str()
                    .replace("@captured@", &entry.captured)
                    .replace("@name@", &entry.name)
                    .replace("@name-expr@", &entry.name_expr)
                    .replace("@dtype@", &entry.dtype);
                tmpstr.push_str(&fmtstr);
            }
            output = re.replace(&output, tmpstr.as_str()).into_owned();
        }
    }
    if template.contains("@static-global-vars@") {
        let re =
            Regex::new(r"@static-global-vars@(?P<fmt>[\S\s]*)@end-static-global-vars@").unwrap();
        for cap in re.captures_iter(template) {
            let mut tmpstr = String::new();
            for entry in &parser.static_vars {
                if !entry.is_local {
                    let fmtstr = cap
                        .name("fmt")
                        .unwrap()
                        .as_str()
                        .replace("@captured@", &entry.captured)
                        .replace("@name@", &entry.name)
                        .replace("@name-expr@", &entry.name_expr)
                        .replace("@dtype@", &entry.dtype);
                    tmpstr.push_str(&fmtstr);
                }
            }
            output = re.replace(&output, tmpstr.as_str()).into_owned();
        }
    }
    if template.contains("@static-local-vars@") {
        let re = Regex::new(r"@static-local-vars@(?P<fmt>[\S\s]*)@end-static-local-vars@").unwrap();
        for cap in re.captures_iter(template) {
            let mut tmpstr = String::new();
            for entry in &parser.static_vars {
                if entry.is_local {
                    let fmtstr = cap
                        .name("fmt")
                        .unwrap()
                        .as_str()
                        .replace("@captured@", &entry.captured)
                        .replace("@name@", &entry.name)
                        .replace("@name-expr@", &entry.name_expr)
                        .replace("@func-name@", &entry.func_name)
                        .replace("@dtype@", &entry.dtype);
                    tmpstr.push_str(&fmtstr);
                }
            }
            output = re.replace(&output, tmpstr.as_str()).into_owned();
        }
    }
    let fncs_tags = vec!["fncs", "fncs0"];
    for tag in fncs_tags {
        let regstr = format!("@{}@{}@end-{}@", tag, r"(?P<fmt>[\S\s]*)", tag);
        let re = Regex::new(&regstr).unwrap();
        for cap in re.captures_iter(template) {
            let mut tmpstr = String::new();
            for entry in &parser.fncs {
                let fmtstr = cap
                    .name("fmt")
                    .unwrap()
                    .as_str()
                    .replace("@captured@", &entry.captured)
                    .replace("@name@", &entry.name)
                    .replace("@rtype@", &entry.rtype)
                    .replace("@args@", &entry.args)
                    .replace("@atypes@", &entry.atypes);
                tmpstr.push_str(&fmtstr);
            }
            output = re.replace(&output, tmpstr.as_str()).into_owned();
        }
    }
    if output.contains("@local-fncs@") {
        let re = Regex::new(r"@local-fncs@(?P<fmt>[\S\s]*)@end-local-fncs@").unwrap();
        for cap in re.captures_iter(template) {
            let mut tmpstr = String::new();
            for entry in &parser.fncs {
                if entry.is_local {
                    let fmtstr = cap
                        .name("fmt")
                        .unwrap()
                        .as_str()
                        .replace("@captured@", &entry.captured)
                        .replace("@name@", &entry.name)
                        .replace("@rtype@", &entry.rtype)
                        .replace("@args@", &entry.args)
                        .replace("@atypes@", &entry.atypes);
                    tmpstr.push_str(&fmtstr);
                }
            }
            output = re.replace(&output, tmpstr.as_str()).into_owned();
        }
    }
    let ncls_tags = vec!["ncls", "ncls-once"];
    for tag in ncls_tags {
        let regstr = format!("@{}@{}@end-{}@", tag, r"(?P<fmt>[\S\s]*)", tag);
        let re = Regex::new(&regstr).unwrap();
        for cap in re.captures_iter(template) {
            let mut tmpstr = String::new();
            let mut callee_list: Vec<String> = Vec::new();
            for entry in &parser.ncls {
                if tag == "ncls-once" {
                    if callee_list.contains(&entry.callee.name) {
                        continue;
                    }
                    callee_list.push(entry.callee.name.to_string());
                }
                let mut fmtstr = cap
                    .name("fmt")
                    .unwrap()
                    .as_str()
                    .replace("@callee.name@", &entry.callee.name)
                    .replace("@callee.rtype@", &entry.callee.rtype)
                    .replace("@callee.args@", &entry.callee.args)
                    .replace("@callee.atypes@", &entry.callee.atypes)
                    .replace("@caller.name@", &entry.caller.name)
                    .replace("@caller.rtype@", &entry.caller.rtype)
                    .replace("@caller.args@", &entry.caller.args)
                    .replace("@caller.atypes@", &entry.caller.atypes);
                let re4change = Regex::new(
                    r"@callee.rtype.change\((?P<from>[a-z|A-Z|0-9|_]+)=(?P<to>[a-z|A-Z|0-9|_]+)\)@",
                )
                .unwrap();
                for cap in re4change.captures_iter(fmtstr.clone().as_str()) {
                    if cap.name("from").unwrap().as_str() == entry.callee.rtype.as_str() {
                        let to = cap.name("to").unwrap().as_str();
                        fmtstr = re4change.replace(&fmtstr, to).into_owned();
                    } else {
                        fmtstr = re4change.replace(&fmtstr, &entry.callee.rtype).into_owned();
                    }
                }
                // remove tags for callee.rtype
                let remove_tags = vec!["callee.rtype.remove", "callee.rtype.remove0"];
                for tag in remove_tags {
                    let regstr = format!(r"@{}\((?P<text>[^)]+)\)@", tag);
                    let re = Regex::new(&regstr).unwrap();
                    for cap in re.captures_iter(fmtstr.clone().as_str()) {
                        if entry.callee.rtype.as_str() == "void" {
                            fmtstr = re.replace(&fmtstr, "").into_owned();
                        } else {
                            let text = cap.name("text").unwrap().as_str();
                            fmtstr = re.replace(&fmtstr, text).into_owned();
                        }
                    }
                }
                // remove tag for callee.args
                let remove_tag = "callee.args.remove";
                let regstr = format!(r"@{}\((?P<text>[^)]+)\)@", remove_tag);
                let re = Regex::new(&regstr).unwrap();
                for cap in re.captures_iter(fmtstr.clone().as_str()) {
                    if entry.callee.args.as_str() == "void" || entry.callee.args.as_str() == "" {
                        fmtstr = re.replace(&fmtstr, "").into_owned();
                    } else {
                        let text = cap.name("text").unwrap().as_str();
                        fmtstr = re.replace(&fmtstr, text).into_owned();
                    }
                }
                tmpstr.push_str(&fmtstr);
            }
            output = re.replace(&output, tmpstr.as_str()).into_owned();
        }
    }
    output.replace("@sourcename@", sourcename).replace(
        "@date@",
        Utc::now().format("%a %b %e %T %Y").to_string().as_str(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_incs() {
        let sourcename = "test";
        let code = "\
#include <header1.h>
#include <header2.h>
";
        let temp = "\
// include
@incs@@captured@
@end-incs@
";
        let expected = "\
// include
#include <header1.h>
#include <header2.h>

";
        let parser = Parser::parse(code);
        let generated = generate(&parser, temp, sourcename);
        assert_eq!(generated, expected);
    }

    #[test]
    fn test_generate_static_vars() {
        let sourcename = "test";
        let code = "\
static int a[10];
int b;
static char *c;
void func1(void)
{
    static int local_var;
}
";
        let temp = "\
// static variables
@static-vars@@dtype@ @name-expr@;
@end-static-vars@
// static global variables
@static-global-vars@@dtype@ @name@;
@end-static-global-vars@
// static local variables
@static-local-vars@@dtype@ @name@;
@end-static-local-vars@
";
        let expected = "\
// static variables
int a[10];
char * c;
int local_var;

// static global variables
int a;
char * c;

// static local variables
int local_var;

";
        let parser = Parser::parse(code);
        let generated = generate(&parser, temp, sourcename);
        assert_eq!(generated, expected);
    }

    #[test]
    fn test_generate_fncs() {
        let sourcename = "test";
        let code = "\
// functions
int func1()
{
    return 0;
}
void func2(int const * a)
{
}
";
        let temp = "\
// functions
@fncs@@rtype@ @name@(@args@);
@atypes@
@end-fncs@
";
        let expected = "\
// functions
int func1();

void func2(int const * a);
const int *

";
        let parser = Parser::parse(code);
        let generated = generate(&parser, temp, sourcename);
        assert_eq!(generated, expected);
    }

    #[test]
    fn test_generate_ncls() {
        let sourcename = "test";
        let code = "\
// functions
void func1()
{
    return;
}
int func2(int a)
{
    return func1();
}
";
        let temp = "\
@ncls@- @caller.name@ -> @callee.name@
    - return @callee.rtype.remove(0)@;
    - (int dummy@callee.args.remove(, )@@callee.args@);
@end-ncls@
";
        let expected = "\
- func2 -> func1
    - return ;
    - (int dummy);

";
        let parser = Parser::parse(code);
        let generated = generate(&parser, temp, sourcename);
        assert_eq!(generated, expected);
    }

    #[test]
    fn test_generate_ncls_once() {
        let sourcename = "test";
        let code = "\
// functions
int func1()
{
    return 0;
}
void func2(int a)
{
    func1();
}
void func3(int a)
{
    func1();
}
";
        let temp = "\
@ncls-once@- @callee.name@
@end-ncls-once@
";
        let expected = "\
- func1

";
        let parser = Parser::parse(code);
        let generated = generate(&parser, temp, sourcename);
        assert_eq!(generated, expected);
    }
}