sigil-stitch 0.3.1

Type-safe, import-aware, width-aware code generation for multiple languages
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
//! Property specification with getter/setter support.
//!
//! `PropertySpec` renders computed properties in two styles:
//!
//! - **Accessor** (TS/JS and fallback): `get name(): T { ... }` / `set name(v: T) { ... }`
//! - **Field** (Swift/Kotlin): field with inline `get`/`set` body blocks

use crate::code_block::{Arg, CodeBlock};
use crate::lang::CodeLang;
use crate::spec::annotation_spec::AnnotationSpec;
use crate::spec::modifiers::{DeclarationContext, Modifiers, PropertyStyle, Visibility};
use crate::type_name::TypeName;

/// A setter definition: parameter name + body.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SetterSpec {
    pub(crate) param_name: String,
    pub(crate) body: CodeBlock,
}

/// A computed property with optional getter and setter.
///
/// `PropertySpec` renders computed properties in two styles depending on the
/// target language:
///
/// - **Accessor** (TS/JS and fallback): `get name(): T { ... }` / `set name(v: T) { ... }`
/// - **Field** (Swift/Kotlin): field with inline `get`/`set` body blocks
///
/// Use [`PropertySpec::builder()`] to construct, then add to a
/// [`TypeSpec`](crate::spec::type_spec::TypeSpec) with `add_property()`.
///
/// # Examples
///
/// ```
/// use sigil_stitch::prelude::*;
/// use sigil_stitch::spec::property_spec::PropertySpec;
/// use sigil_stitch::lang::typescript::TypeScript;
///
/// let getter_body = CodeBlock::of("return this._name", ()).unwrap();
///
/// let prop = PropertySpec::builder("name", TypeName::primitive("string"))
///     .getter(getter_body)
///     .build().unwrap();
/// ```
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PropertySpec {
    pub(crate) name: String,
    pub(crate) property_type: TypeName,
    pub(crate) modifiers: Modifiers,
    pub(crate) doc: Vec<String>,
    pub(crate) getter: Option<CodeBlock>,
    pub(crate) setter: Option<SetterSpec>,
    pub(crate) annotations: Vec<CodeBlock>,
    pub(crate) annotation_specs: Vec<AnnotationSpec>,
}

impl PropertySpec {
    /// Create a new builder for a property with the given name and type.
    pub fn builder(name: &str, property_type: TypeName) -> PropertySpecBuilder {
        PropertySpecBuilder {
            name: name.to_string(),
            property_type,
            modifiers: Modifiers::default(),
            doc: Vec::new(),
            getter: None,
            setter: None,
            annotations: Vec::new(),
            annotation_specs: Vec::new(),
        }
    }

    /// Return the property name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Emit this property as one or more CodeBlocks.
    ///
    /// Accessor style returns 1–2 blocks (getter, setter).
    /// Field style returns 1 block (field with inline body).
    pub fn emit(
        &self,
        lang: &dyn CodeLang,
        ctx: DeclarationContext,
    ) -> Result<Vec<CodeBlock>, crate::error::SigilStitchError> {
        match lang.property_style() {
            PropertyStyle::Accessor => self.emit_accessor(lang, ctx),
            PropertyStyle::Field => self.emit_field(lang, ctx),
        }
    }

    /// Emit as accessor methods: `get name(): T { ... }` / `set name(v: T) { ... }`.
    fn emit_accessor(
        &self,
        lang: &dyn CodeLang,
        ctx: DeclarationContext,
    ) -> Result<Vec<CodeBlock>, crate::error::SigilStitchError> {
        let mut blocks = Vec::new();

        if let Some(getter_body) = &self.getter {
            let mut cb = CodeBlock::builder();

            // Annotations + doc on the getter.
            self.emit_preamble(&mut cb, lang)?;

            // Signature: [vis] get [name]()[return_type_sep][type][block_open]
            let vis = lang.render_visibility(self.modifiers.visibility, ctx);
            let mut sig = String::new();
            let mut sig_args: Vec<Arg> = Vec::new();

            sig.push_str(vis);
            if self.modifiers.is_static {
                sig.push_str("static ");
            }
            sig.push_str("get ");
            sig.push_str(&self.name);
            sig.push_str("()");

            if !self.property_type.is_empty() {
                sig.push_str(lang.function_syntax().return_type_separator);
                sig.push_str("%T");
                sig_args.push(Arg::TypeName(self.property_type.clone()));
            }

            sig.push_str(lang.block_syntax().block_open);
            cb.add(&sig, sig_args);
            cb.add_line();
            cb.add("%>", ());
            cb.add_code(getter_body.clone());
            cb.add_line();
            cb.add("%<", ());
            let close = lang.block_syntax().block_close;
            if !close.is_empty() {
                cb.add(close, ());
                cb.add_line();
            }

            blocks.push(cb.build()?);
        }

        if let Some(setter) = &self.setter {
            let mut cb = CodeBlock::builder();

            // Setter signature: [vis] set [name]([param][sep][type])[block_open]
            let vis = lang.render_visibility(self.modifiers.visibility, ctx);
            let mut sig = String::new();
            let mut sig_args: Vec<Arg> = Vec::new();

            sig.push_str(vis);
            if self.modifiers.is_static {
                sig.push_str("static ");
            }
            sig.push_str("set ");
            sig.push_str(&self.name);
            sig.push('(');
            sig.push_str(&lang.escape_reserved(&setter.param_name));

            if !self.property_type.is_empty() {
                sig.push_str(lang.type_decl_syntax().type_annotation_separator);
                sig.push_str("%T");
                sig_args.push(Arg::TypeName(self.property_type.clone()));
            }

            sig.push(')');
            sig.push_str(lang.block_syntax().block_open);
            cb.add(&sig, sig_args);
            cb.add_line();
            cb.add("%>", ());
            cb.add_code(setter.body.clone());
            cb.add_line();
            cb.add("%<", ());
            let close = lang.block_syntax().block_close;
            if !close.is_empty() {
                cb.add(close, ());
                cb.add_line();
            }

            blocks.push(cb.build()?);
        }

        Ok(blocks)
    }

    /// Emit as a field with inline getter/setter body (Swift/Kotlin).
    fn emit_field(
        &self,
        lang: &dyn CodeLang,
        ctx: DeclarationContext,
    ) -> Result<Vec<CodeBlock>, crate::error::SigilStitchError> {
        let mut cb = CodeBlock::builder();

        // Annotations + doc.
        self.emit_preamble(&mut cb, lang)?;

        // Field header: [vis] [var/let] [name]: [type] {
        let vis = lang.render_visibility(self.modifiers.visibility, ctx);
        let has_setter = self.setter.is_some();

        let mut sig = String::new();
        let mut sig_args: Vec<Arg> = Vec::new();

        sig.push_str(vis);
        if self.modifiers.is_static {
            sig.push_str("static ");
        }

        if has_setter {
            sig.push_str(lang.enum_and_annotation().mutable_field_keyword);
        } else {
            sig.push_str(lang.enum_and_annotation().readonly_keyword);
        }

        sig.push_str(&lang.escape_reserved(&self.name));

        if !self.property_type.is_empty() {
            sig.push_str(lang.type_decl_syntax().type_annotation_separator);
            sig.push_str("%T");
            sig_args.push(Arg::TypeName(self.property_type.clone()));
        }

        sig.push_str(lang.block_syntax().block_open);
        cb.add(&sig, sig_args);
        cb.add_line();
        cb.add("%>", ());

        // Getter block.
        if let Some(getter_body) = &self.getter {
            let getter_kw = lang.property_getter_keyword();
            let getter_sig = format!("{getter_kw}{}", lang.block_syntax().block_open);
            cb.add(&getter_sig, ());
            cb.add_line();
            cb.add("%>", ());
            cb.add_code(getter_body.clone());
            cb.add_line();
            cb.add("%<", ());
            let close = lang.block_syntax().block_close;
            if !close.is_empty() {
                cb.add(close, ());
                cb.add_line();
            }
        }

        // Setter block.
        if let Some(setter) = &self.setter {
            let setter_sig = format!(
                "set({}){}",
                setter.param_name,
                lang.block_syntax().block_open
            );
            cb.add(&setter_sig, ());
            cb.add_line();
            cb.add("%>", ());
            cb.add_code(setter.body.clone());
            cb.add_line();
            cb.add("%<", ());
            let close = lang.block_syntax().block_close;
            if !close.is_empty() {
                cb.add(close, ());
                cb.add_line();
            }
        }

        cb.add("%<", ());
        let close = lang.block_syntax().block_close;
        if !close.is_empty() {
            cb.add(close, ());
            cb.add_line();
        }

        Ok(vec![cb.build()?])
    }

    /// Emit annotations and doc comment as a preamble.
    fn emit_preamble(
        &self,
        cb: &mut crate::code_block::CodeBlockBuilder,
        lang: &dyn CodeLang,
    ) -> Result<(), crate::error::SigilStitchError> {
        let emit_doc = || -> Option<String> {
            if self.doc.is_empty() || lang.doc_comment_inside_body() {
                return None;
            }
            let doc_lines: Vec<&str> = self.doc.iter().map(|s| s.as_str()).collect();
            Some(lang.render_doc_comment(&doc_lines))
        };

        if lang.doc_before_annotations()
            && let Some(doc_str) = emit_doc()
        {
            cb.add("%L", doc_str);
            cb.add_line();
        }

        for spec in &self.annotation_specs {
            cb.add_code(spec.emit(lang)?);
            cb.add_line();
        }
        for ann in &self.annotations {
            cb.add_code(ann.clone());
            cb.add_line();
        }

        if !lang.doc_before_annotations()
            && let Some(doc_str) = emit_doc()
        {
            cb.add("%L", doc_str);
            cb.add_line();
        }

        Ok(())
    }
}

/// Builder for [`PropertySpec`].
#[derive(Debug)]
pub struct PropertySpecBuilder {
    name: String,
    property_type: TypeName,
    modifiers: Modifiers,
    doc: Vec<String>,
    getter: Option<CodeBlock>,
    setter: Option<SetterSpec>,
    annotations: Vec<CodeBlock>,
    annotation_specs: Vec<AnnotationSpec>,
}

impl PropertySpecBuilder {
    /// Set the getter body.
    pub fn getter(mut self, body: CodeBlock) -> Self {
        self.getter = Some(body);
        self
    }

    /// Set the setter parameter name and body.
    pub fn setter(mut self, param_name: &str, body: CodeBlock) -> Self {
        self.setter = Some(SetterSpec {
            param_name: param_name.to_string(),
            body,
        });
        self
    }

    /// Set the visibility.
    pub fn visibility(mut self, vis: Visibility) -> Self {
        self.modifiers.visibility = vis;
        self
    }

    /// Mark this property as static.
    pub fn is_static(mut self) -> Self {
        self.modifiers.is_static = true;
        self
    }

    /// Add a doc comment line.
    pub fn doc(mut self, line: &str) -> Self {
        self.doc.push(line.to_string());
        self
    }

    /// Add a raw annotation code block.
    pub fn annotation(mut self, ann: CodeBlock) -> Self {
        self.annotations.push(ann);
        self
    }

    /// Add a structured annotation.
    pub fn annotate(mut self, spec: AnnotationSpec) -> Self {
        self.annotation_specs.push(spec);
        self
    }

    /// Build the [`PropertySpec`].
    ///
    /// # Errors
    ///
    /// Returns [`SigilStitchError::EmptyName`](crate::error::SigilStitchError::EmptyName) if `name` is empty.
    pub fn build(self) -> Result<PropertySpec, crate::error::SigilStitchError> {
        snafu::ensure!(
            !self.name.is_empty(),
            crate::error::EmptyNameSnafu {
                builder: "PropertySpecBuilder",
            }
        );
        Ok(PropertySpec {
            name: self.name,
            property_type: self.property_type,
            modifiers: self.modifiers,
            doc: self.doc,
            getter: self.getter,
            setter: self.setter,
            annotations: self.annotations,
            annotation_specs: self.annotation_specs,
        })
    }
}

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

    #[test]
    fn test_build_empty_name_errors() {
        let result = PropertySpec::builder("", TypeName::primitive("string")).build();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("'name' must not be empty")
        );
    }
}