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
//! Specialization for Dart code generation.
//!
//! # String Quoting in Dart
//!
//! Since Java uses UTF-16 internally, string quoting for high unicode
//! characters is done through surrogate pairs, as seen with the 😊 below.
//!
//! ```rust
//! use genco::prelude::*;
//!
//! # fn main() -> genco::fmt::Result {
//! let toks: dart::Tokens = quote!("start π 😊 \n \x7f ÿ $ \\ end");
//! assert_eq!("\"start π 😊 \\n \\x7f ÿ \\$ \\\\ end\"", toks.to_string()?);
//! # Ok(())
//! # }
//! ```
//!
//! # String Interpolation in Dart
//!
//! Strings can be interpolated in Dart, by using the special `$_(<string>)`
//! escape sequence.
//!
//! ```rust
//! use genco::prelude::*;
//!
//! # fn main() -> genco::fmt::Result {
//! let toks: dart::Tokens = quote!($[str](  Hello: $var  ));
//! assert_eq!("\"  Hello: $var  \"", toks.to_string()?);
//!
//! let toks: dart::Tokens = quote!($[str](  Hello: $(a + b)  ));
//! assert_eq!("\"  Hello: ${a + b}  \"", toks.to_string()?);
//! # Ok(())
//! # }
//! ```

mod doc_comment;

pub use self::doc_comment::DocComment;

use crate as genco;
use crate::fmt;
use crate::quote_in;
use crate::tokens::{quoted, ItemStr};
use std::fmt::Write as _;

const SEP: &str = ".";
/// dart:core package.
const DART_CORE: &str = "dart:core";

/// Tokens container specialization for Dart.
pub type Tokens = crate::Tokens<Dart>;

impl genco::lang::LangSupportsEval for Dart {}

impl_lang! {
    /// Language specialization for Dart.
    pub Dart {
        type Config = Config;
        type Format = Format;
        type Item = Import;

        fn string_eval_literal(
            out: &mut fmt::Formatter<'_>,
            _config: &Self::Config,
            _format: &Self::Format,
            literal: &str,
        ) -> fmt::Result {
            write!(out, "${}", literal)?;
            Ok(())
        }

        /// Start a string-interpolated eval.
        fn start_string_eval(
            out: &mut fmt::Formatter<'_>,
            _config: &Self::Config,
            _format: &Self::Format,
        ) -> fmt::Result {
            out.write_str("${")?;
            Ok(())
        }

        /// End a string interpolated eval.
        fn end_string_eval(
            out: &mut fmt::Formatter<'_>,
            _config: &Self::Config,
            _format: &Self::Format,
        ) -> fmt::Result {
            out.write_char('}')?;
            Ok(())
        }

        fn write_quoted(out: &mut fmt::Formatter<'_>, input: &str) -> fmt::Result {
            // Note: Dart is like C escape, but since it supports string
            // interpolation, `$` also needs to be escaped!

            for c in input.chars() {
                match c {
                    // backspace
                    '\u{0008}' => out.write_str("\\b")?,
                    // form feed
                    '\u{0012}' => out.write_str("\\f")?,
                    // new line
                    '\n' => out.write_str("\\n")?,
                    // carriage return
                    '\r' => out.write_str("\\r")?,
                    // horizontal tab
                    '\t' => out.write_str("\\t")?,
                    // vertical tab
                    '\u{0011}' => out.write_str("\\v")?,
                    // Note: only relevant if we were to use single-quoted strings.
                    // '\'' => out.write_str("\\'")?,
                    '"' => out.write_str("\\\"")?,
                    '\\' => out.write_str("\\\\")?,
                    '$' => out.write_str("\\$")?,
                    c if !c.is_control() => out.write_char(c)?,
                    c if (c as u32) < 0x100 => {
                        write!(out, "\\x{:02x}", c as u32)?;
                    }
                    c => {
                        for c in c.encode_utf16(&mut [0u16; 2]) {
                            write!(out, "\\u{:04x}", c)?;
                        }
                    }
                };
            }

            Ok(())
        }

        fn format_file(
            tokens: &Tokens,
            out: &mut fmt::Formatter<'_>,
            config: &Self::Config,
        ) -> fmt::Result {
            let mut imports: Tokens = Tokens::new();
            Self::imports(&mut imports, tokens, config);
            let format = Format::default();
            imports.format(out, config, &format)?;
            tokens.format(out, config, &format)?;
            Ok(())
        }
    }

    Import {
        fn format(&self, out: &mut fmt::Formatter<'_>, _: &Config, _: &Format) -> fmt::Result {
            if let Some(alias) = &self.alias {
                out.write_str(alias.as_ref())?;
                out.write_str(SEP)?;
            }

            out.write_str(&self.name)?;
            Ok(())
        }
    }
}

/// Format state for Dart.
#[derive(Debug, Default)]
pub struct Format {}

/// Config data for Dart formatting.
#[derive(Debug, Default)]
pub struct Config {}

/// The import of a Dart type `import "dart:math";`.
///
/// Created through the [import()] function.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Import {
    /// Path to import.
    path: ItemStr,
    /// Name imported.
    name: ItemStr,
    /// Alias of module.
    alias: Option<ItemStr>,
}

impl Import {
    /// Add an `as` keyword to the import.
    pub fn with_alias(self, alias: impl Into<ItemStr>) -> Import {
        Self {
            alias: Some(alias.into()),
            ..self
        }
    }
}

impl Dart {
    /// Resolve all imports.
    fn imports(out: &mut Tokens, input: &Tokens, _: &Config) {
        use std::collections::BTreeSet;

        let mut modules = BTreeSet::new();

        for import in input.walk_imports() {
            if &*import.path == DART_CORE {
                continue;
            }

            modules.insert((import.path.clone(), import.alias.clone()));
        }

        if modules.is_empty() {
            return;
        }

        for (name, alias) in modules {
            if let Some(alias) = alias {
                quote_in!(*out => import $(quoted(name)) as $alias;);
            } else {
                quote_in!(*out => import $(quoted(name)););
            }

            out.push();
        }

        out.line();
    }
}

/// The import of a Dart type `import "dart:math";`.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let a = dart::import("package:http/http.dart", "A");
/// let b = dart::import("package:http/http.dart", "B");
/// let c = dart::import("package:http/http.dart", "C").with_alias("h2");
/// let d = dart::import("../http.dart", "D");
///
/// let toks = quote! {
///     $a
///     $b
///     $c
///     $d
/// };
///
/// let expected = vec![
///     "import \"../http.dart\";",
///     "import \"package:http/http.dart\";",
///     "import \"package:http/http.dart\" as h2;",
///     "",
///     "A",
///     "B",
///     "h2.C",
///     "D",
/// ];
///
/// assert_eq!(expected, toks.to_file_vec()?);
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn import<P, N>(path: P, name: N) -> Import
where
    P: Into<ItemStr>,
    N: Into<ItemStr>,
{
    Import {
        path: path.into(),
        alias: None,
        name: name.into(),
    }
}

/// Format a doc comment where each line is preceeded by `///`.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
/// use std::iter;
///
/// let toks = quote! {
///     $(dart::doc_comment(vec!["Foo"]))
///     $(dart::doc_comment(iter::empty::<&str>()))
///     $(dart::doc_comment(vec!["Bar"]))
/// };
///
/// assert_eq!(
///     vec![
///         "/// Foo",
///         "/// Bar",
///     ],
///     toks.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn doc_comment<T>(comment: T) -> DocComment<T>
where
    T: IntoIterator,
    T::Item: Into<ItemStr>,
{
    DocComment(comment)
}