crustal 0.3.6

A library for generating C/C++ code.
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// C/C++ Code Generator For Rust
//
//
// MIT License
//
// Copyright (c) 2022 Reto Achermann
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! # Class Constructors and Destructors
//!
//! This module contains definitions for C++ class constructors and destructors

use std::fmt::{self, Write};

use crate::{BaseType, Block, Doc, Expr, Formatter, MethodParam, Type, Visibility};

/// holds a method definition
#[derive(Debug, Clone)]
pub struct Constructor {
    /// Name of the method
    name: String,

    /// the visibility of the method
    visibility: Visibility,

    /// the method documentation
    doc: Option<Doc>,

    /// the method arguments
    params: Vec<MethodParam>,

    /// the initalizer list
    initializers: Vec<Expr>,

    /// this is the default constructor
    is_default: bool,

    /// marks the constructor as deleted
    is_delete: bool,

    /// this is a copy constructor
    is_copy: bool,

    /// this is a move contstructor
    is_move: bool,

    /// wheter the definition is inside of the class
    is_inside: bool,

    /// the body of the method, a sequence of statements
    body: Block,
}

impl Constructor {
    /// Creates a new constructor definition
    pub fn new(name: &str) -> Self {
        Self {
            name: String::from(name),
            doc: None,
            visibility: Visibility::Public,
            params: Vec::new(),
            initializers: Vec::new(),
            is_default: false,
            is_delete: false,
            is_copy: false,
            is_move: false,
            is_inside: false,
            body: Block::new(),
        }
    }

    /// creates a new move constructor
    pub fn new_move(name: &str) -> Self {
        let mut c = Constructor::new(name);
        c.is_move = true;
        c
    }

    /// creates a new copy constructor
    pub fn new_copy(name: &str) -> Self {
        let mut c = Constructor::new(name);
        c.is_copy = true;
        c
    }

    /// creates a new copy constructor
    pub fn new_default(name: &str) -> Self {
        let mut c = Constructor::new(name);
        c.is_default = true;
        c
    }

    /// creates a new copy constructor
    pub fn new_delete(name: &str) -> Self {
        let mut c = Constructor::new(name);
        c.is_delete = true;
        c
    }

    /// adds a string to the documentation comment to the variant
    pub fn doc_str(&mut self, doc: &str) -> &mut Self {
        if let Some(d) = &mut self.doc {
            d.add_text(doc);
        } else {
            self.doc = Some(Doc::with_str(doc));
        }
        self
    }

    /// adds a documetnation comment to the variant
    pub fn add_doc(&mut self, doc: Doc) -> &mut Self {
        self.doc = Some(doc);
        self
    }

    /// sets the visibility of the method
    pub fn set_visibility(&mut self, vis: Visibility) -> &mut Self {
        self.visibility = vis;
        self
    }

    /// tests if the method is private
    pub fn is_public(&self) -> bool {
        self.visibility == Visibility::Public
    }

    /// tests if the method is protected
    pub fn is_protected(&self) -> bool {
        self.visibility == Visibility::Protected
    }

    /// tests if the method is private
    pub fn is_private(&self) -> bool {
        self.visibility == Visibility::Private || self.visibility == Visibility::Default
    }

    /// sets the visibility to public
    pub fn public(&mut self) -> &mut Self {
        self.set_visibility(Visibility::Public)
    }

    /// sets the visibility to protected
    pub fn protected(&mut self) -> &mut Self {
        self.set_visibility(Visibility::Protected)
    }

    /// sets the visibility to private
    pub fn private(&mut self) -> &mut Self {
        self.set_visibility(Visibility::Private)
    }

    /// adds an param to the method
    pub fn push_param(&mut self, arg: MethodParam) -> &mut Self {
        self.params.push(arg);
        self
    }

    pub fn new_param(&mut self, name: &str, ty: Type) -> &mut MethodParam {
        self.push_param(MethodParam::new(name, ty));
        self.params.last_mut().unwrap()
    }

    /// obtains a reference to the param with the given name
    pub fn param_by_name(&self, name: &str) -> Option<&MethodParam> {
        self.params.iter().find(|f| f.name() == name)
    }

    /// obtains a mutable reference to the param with the given name
    pub fn param_by_name_mut(&mut self, name: &str) -> Option<&mut MethodParam> {
        self.params.iter_mut().find(|f| f.name() == name)
    }

    /// obtains a reference to the param with the given index (starting at 0)
    pub fn param_by_idx(&self, idx: usize) -> Option<&MethodParam> {
        self.params.get(idx)
    }

    /// obtains a mutable reference to the param with the given index mut
    pub fn param_by_idx_mut(&mut self, idx: usize) -> Option<&mut MethodParam> {
        self.params.get_mut(idx)
    }

    /// pushes a new elemenet to the initializer list
    pub fn push_initializer(&mut self, field_name: &str, value: Expr) -> &mut Self {
        self.initializers.push(Expr::FnCall {
            name: String::from(field_name),
            args: vec![value],
        });
        self
    }

    pub fn push_parent_initializer(&mut self, value: Expr) -> &mut Self {
        self.initializers.push(value);
        self
    }

    /// sets the constructor to be default
    ///
    /// # Example
    ///
    /// Foo()   -> Foo() = default
    pub fn set_default(&mut self, val: bool) -> &mut Self {
        if val {
            self.body.clear();
            if !self.is_copy {
                self.params.clear();
            }
            self.is_delete = false;
        }
        self.is_default = val;
        self
    }

    /// makes the constructor the default one
    pub fn default(&mut self) -> &mut Self {
        self.set_default(true)
    }

    /// sets the constructor to be deleted
    ///
    /// # Example
    ///
    /// Foo()   -> Foo() = delete;
    pub fn set_delete(&mut self, val: bool) -> &mut Self {
        if val {
            self.body.clear();
            if !self.is_copy {
                self.params.clear();
            }
            self.is_default = false;
        }
        self.is_delete = val;
        self
    }

    /// makes the constructor the default one
    pub fn delete(&mut self) -> &mut Self {
        self.set_delete(true)
    }

    /// marks this constructor as the copy constructor
    ///
    /// # Example
    ///
    /// Foo()   -> Foo(const Foo&)
    pub fn set_copy(&mut self, val: bool) -> &mut Self {
        if val {
            let mut ty = Type::new(BaseType::Class(self.name.clone()));
            ty.constant().reference();
            self.params = vec![MethodParam::new("other", ty)];
        }
        self.is_copy = val;
        self
    }

    /// makes the method to be an static method
    pub fn copy(&mut self) -> &mut Self {
        self.set_copy(true)
    }

    /// marks this constructor as the move constructor
    ///
    /// # Example
    ///
    /// Foo()   -> Foo(Foo &&)
    pub fn set_move(&mut self, val: bool) -> &mut Self {
        if val {
            let mut ty = Type::new(BaseType::Class(self.name.clone()));
            ty.reference().reference();
            self.params = vec![MethodParam::new("other", ty)];
        }
        self.is_move = val;
        self
    }

    /// makes the method to be an static method
    pub fn movec(&mut self) -> &mut Self {
        self.set_move(true)
    }

    /// sets the definition localtion of the method
    pub fn set_inside_def(&mut self, val: bool) -> &mut Self {
        self.is_inside = val;
        self
    }

    /// this method is defined inside
    pub fn inside_def(&mut self) -> &mut Self {
        self.set_inside_def(true)
    }

    /// sets the body for the method
    pub fn set_body(&mut self, body: Block) -> &mut Self {
        if !body.is_empty() {
            self.is_default = false;
            self.is_delete = false;
        }
        self.body = body;
        self
    }

    /// obtains reference to the body lock
    pub fn body(&mut self) -> &mut Block {
        &mut self.body
    }

    /// Formats the attribute using the given formatter.
    pub fn do_fmt(&self, fmt: &mut Formatter<'_>, decl_only: bool) -> fmt::Result {
        if !self.body.is_empty() | self.doc.is_some() {
            writeln!(fmt)?;
        }

        if let Some(ref docs) = self.doc {
            docs.fmt(fmt)?;
        }

        if decl_only {
            write!(fmt, "{}", self.name)?;
        } else {
            fmt.write_scoped_name(self.name.as_str())?;
        }

        if self.params.is_empty() {
            write!(fmt, "(void)")?;
        } else {
            write!(fmt, "(")?;
            for (i, arg) in self.params.iter().enumerate() {
                if i != 0 {
                    write!(fmt, ", ")?;
                }
                arg.do_fmt(fmt, decl_only)?;
            }
            write!(fmt, ")")?;
        }

        if self.body.is_empty() && self.is_default {
            return writeln!(fmt, " = default;");
        }

        if self.body.is_empty() && self.is_delete {
            return writeln!(fmt, " = delete;");
        }

        // if we want to have the declaration only, then do that,
        // but only if it's not a inside method or an inline method
        if decl_only && !(self.is_inside) {
            return writeln!(fmt, ";");
        }

        writeln!(fmt)?;
        if !self.initializers.is_empty() && (!decl_only || self.is_inside) {
            fmt.indent(|fmt| {
                write!(fmt, ": ").expect("initializer");
                for (i, e) in self.initializers.iter().enumerate() {
                    if i != 0 {
                        write!(fmt, ", ").expect("initializer");
                    }
                    e.fmt(fmt).expect("initializer");
                    writeln!(fmt).expect("initializer");
                }
            })
        }

        fmt.block(|f| self.body.fmt(f))?;
        writeln!(fmt)
    }

    /// formats the method definition
    pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        self.do_fmt(fmt, false)
    }

    /// formats the method declaration
    pub fn fmt_decl(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        self.do_fmt(fmt, true)
    }

    /// formats the method definition
    pub fn fmt_def(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        // inline or inside functions are defined in the declaration
        if self.is_inside {
            return Ok(());
        }
        self.do_fmt(fmt, false)
    }
}

#[derive(Debug, Clone)]
pub struct Destructor {
    /// Name of the method
    name: String,

    /// the method documentation
    doc: Option<Doc>,

    /// this is the default constructor
    is_default: bool,

    /// marks the constructor as deleted
    is_delete: bool,

    /// wheter the definition is inside of the class
    is_inside: bool,

    /// sets the pure
    is_pure: bool,

    /// the body of the method, a sequence of statements
    body: Block,
}

impl Destructor {
    /// Creates a new constructor definition
    pub fn new(name: &str) -> Self {
        Self {
            name: String::from(name),
            doc: None,
            is_default: false,
            is_delete: false,
            is_inside: false,
            is_pure: false,
            body: Block::new(),
        }
    }

    /// creates a new move constructor
    pub fn new_delete(name: &str) -> Self {
        let mut c = Destructor::new(name);
        c.is_delete = true;
        c
    }

    /// creates a new copy constructor
    pub fn new_default(name: &str) -> Self {
        let mut c = Destructor::new(name);
        c.is_default = true;
        c
    }

    /// creates a new copy constructor
    pub fn new_pure(name: &str) -> Self {
        let mut c = Destructor::new(name);
        c.is_pure = true;
        c
    }

    /// adds a string to the documentation comment to the variant
    pub fn doc_str(&mut self, doc: &str) -> &mut Self {
        if let Some(d) = &mut self.doc {
            d.add_text(doc);
        } else {
            self.doc = Some(Doc::with_str(doc));
        }
        self
    }

    /// adds a documetnation comment to the variant
    pub fn add_doc(&mut self, doc: Doc) -> &mut Self {
        self.doc = Some(doc);
        self
    }

    /// sets the constructor to be default
    ///
    /// # Example
    ///
    /// Foo()   -> Foo() = default
    pub fn set_default(&mut self, val: bool) -> &mut Self {
        if val {
            self.is_delete = false;
        }
        self.is_default = val;
        self
    }

    /// makes the constructor the default one
    pub fn default(&mut self) -> &mut Self {
        self.set_default(true)
    }

    /// sets the constructor to be deleted
    ///
    /// # Example
    ///
    /// Foo()   -> Foo() = delete;
    pub fn set_delete(&mut self, val: bool) -> &mut Self {
        if val {
            self.is_default = false;
        }
        self.is_delete = val;
        self
    }

    /// makes the constructor the default one
    pub fn delete(&mut self) -> &mut Self {
        self.set_delete(true)
    }

    /// sets the definition localtion of the method
    pub fn set_inside_def(&mut self, val: bool) -> &mut Self {
        self.is_inside = val;
        self
    }

    /// this method is defined inside
    pub fn inside_def(&mut self) -> &mut Self {
        self.set_inside_def(true)
    }

    /// sets the method to be pure
    ///
    /// # Example
    ///
    /// void foo()   -> virtual void foo() = 0
    pub fn set_pure(&mut self, val: bool) -> &mut Self {
        if val {
            self.body.clear();
        }
        self.is_pure = val;
        self
    }

    /// turns the method into a pure method
    pub fn pure(&mut self) -> &mut Self {
        self.set_pure(true)
    }

    /// sets the body for the method
    pub fn set_body(&mut self, body: Block) -> &mut Self {
        if !body.is_empty() {
            self.is_default = false;
            self.is_delete = false;
            self.is_pure = false;
        }
        self.body = body;
        self
    }

    /// obtains a reference to the body of the destructor
    pub fn body(&mut self) -> &mut Block {
        &mut self.body
    }

    /// Formats the attribute using the given formatter.
    pub fn do_fmt(&self, fmt: &mut Formatter<'_>, decl_only: bool) -> fmt::Result {
        if !self.body.is_empty() | self.doc.is_some() {
            writeln!(fmt)?;
        }

        if let Some(ref docs) = self.doc {
            docs.fmt(fmt)?;
        }

        if self.body.is_empty() && self.is_pure {
            write!(fmt, "virtual ")?;
        }

        write!(fmt, "~{}(void)", self.name)?;

        if self.body.is_empty() && self.is_default {
            return writeln!(fmt, " = default;");
        }

        if self.body.is_empty() && self.is_delete {
            return writeln!(fmt, " = delete;");
        }

        if self.is_pure {
            return writeln!(fmt, " = 0;");
        }

        // if we want to have the declaration only, then do that,
        // but only if it's not a inside method or an inline method
        if self.body.is_empty() || (decl_only && !(self.is_inside)) {
            return writeln!(fmt, ";");
        }

        fmt.block(|fmt| self.body.fmt(fmt))?;
        writeln!(fmt)
    }

    /// formats the method definition
    pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        self.do_fmt(fmt, false)
    }

    /// formats the method declaration
    pub fn fmt_decl(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        self.do_fmt(fmt, true)
    }

    /// formats the method definition
    pub fn fmt_def(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
        // inline or inside functions are defined in the declaration
        if self.is_inside {
            return Ok(());
        }
        self.do_fmt(fmt, false)
    }
}