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
//! Specialization for Dart code generation.

mod modifier;
mod utils;

pub use self::modifier::Modifier;
pub use self::utils::DocComment;

use super::cons::Cons;
use super::custom::Custom;
use super::formatter::Formatter;
use super::into_tokens::IntoTokens;
use super::tokens::Tokens;
use std::fmt::{self, Write};

static SEP: &'static str = ".";
/// dart:core package.
pub static DART_CORE: &'static str = "dart:core";

/// Integer built-in type.
pub const INT: Dart<'static> = Dart::BuiltIn { name: "int" };

/// Double built-in type.
pub const DOUBLE: Dart<'static> = Dart::BuiltIn { name: "double" };

/// Boolean built-in type.
pub const BOOL: Dart<'static> = Dart::BuiltIn { name: "bool" };

/// All information about a single type.
#[derive(Default, Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Type<'el> {
    /// Path to import.
    path: Option<Cons<'el>>,
    /// Alias of module.
    alias: Option<Cons<'el>>,
    /// Name imported.
    name: Option<Cons<'el>>,
    /// Generic arguments.
    arguments: Vec<Dart<'el>>,
}

/// Dart token specialization.
#[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub enum Dart<'el> {
    /// built-in type.
    BuiltIn {
        /// The built-in type.
        name: &'static str,
    },
    /// the void type.
    Void,
    /// the dynamic type.
    Dynamic,
    /// referenced types.
    Type(Type<'el>),
}

into_tokens_impl_from!(Dart<'el>, Dart<'el>);
into_tokens_impl_from!(&'el Dart<'el>, Dart<'el>);

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

impl crate::Config for Config {}

impl<'el> Dart<'el> {
    /// Resolve all imports.
    fn imports<'a, 'b: 'a>(
        input: &'b Tokens<'a, Dart<'el>>,
        _: &mut Config,
    ) -> Tokens<'a, Dart<'el>> {
        use crate::quoted::Quoted;
        use std::collections::BTreeSet;

        let mut modules = BTreeSet::new();

        for custom in input.walk_custom() {
            if let Dart::Type(ref ty) = *custom {
                if let Some(path) = ty.path.as_ref() {
                    if path.as_ref() == DART_CORE {
                        continue;
                    }

                    modules.insert((path.as_ref(), ty.alias.as_ref().map(AsRef::as_ref)));
                }
            }
        }

        if modules.is_empty() {
            return toks!();
        }

        let mut o = toks!();

        for (name, alias) in modules {
            if let Some(alias) = alias {
                o.push(toks!("import ", name.quoted(), " as ", alias, ";"));
            } else {
                o.push(toks!("import ", name.quoted(), ";"));
            }
        }

        return o;
    }

    /// Change the imported alias for this type.
    pub fn alias(&self, alias: impl Into<Cons<'el>>) -> Dart<'el> {
        match *self {
            Dart::Type(ref ty) => Dart::Type(Type {
                alias: Some(alias.into()),
                ..ty.clone()
            }),
            ref dart => dart.clone(),
        }
    }

    /// Change the imported name for this type.
    pub fn name(&self, name: impl Into<Cons<'el>>) -> Dart<'el> {
        match *self {
            Dart::Type(ref ty) => Dart::Type(Type {
                name: Some(name.into()),
                ..ty.clone()
            }),
            ref dart => dart.clone(),
        }
    }

    /// Add arguments to the given variable.
    ///
    /// Only applies to classes, any other will return the same value.
    pub fn with_arguments(&self, arguments: Vec<Dart<'el>>) -> Dart<'el> {
        match *self {
            Dart::Type(ref ty) => Dart::Type(Type {
                arguments: arguments,
                ..ty.clone()
            }),
            ref dart => dart.clone(),
        }
    }

    /// Get the arguments.
    pub fn arguments(&self) -> Option<&[Dart<'el>]> {
        use self::Dart::*;

        match *self {
            Type(ref ty) => Some(&ty.arguments),
            _ => None,
        }
    }

    /// Check if variable is built-in.
    pub fn is_built_in(&self) -> bool {
        use self::Dart::*;

        match *self {
            BuiltIn { .. } => true,
            _ => false,
        }
    }

    /// Convert into raw type.
    /// Raw types have no alias, nor generic arguments.
    pub fn raw(&self) -> Dart<'el> {
        match *self {
            Dart::Type(ref ty) => Dart::Type(Type {
                arguments: vec![],
                alias: None,
                ..ty.clone()
            }),
            ref other => other.clone(),
        }
    }

    /// Check if this type belongs to a core package.
    pub fn is_core(&self) -> bool {
        use self::Dart::*;

        let ty = match *self {
            Type(ref ty) => ty,
            BuiltIn { .. } => return true,
            Void => return true,
            Dynamic => return true,
        };

        match ty.path.as_ref() {
            Some(path) => path.as_ref() == DART_CORE,
            None => false,
        }
    }

    /// Check if type is generic.
    pub fn is_generic(&self) -> bool {
        self.arguments().map(|a| !a.is_empty()).unwrap_or(false)
    }
}

impl<'el> Custom for Dart<'el> {
    type Config = Config;

    fn format(&self, out: &mut Formatter, config: &mut Self::Config, level: usize) -> fmt::Result {
        use self::Dart::*;

        match *self {
            BuiltIn { ref name, .. } => {
                out.write_str(name.as_ref())?;
            }
            Void => out.write_str("void")?,
            Dynamic => out.write_str("dynamic")?,
            Type(ref ty) => {
                if let Some(ref name) = ty.name {
                    if let Some(ref alias) = ty.alias {
                        out.write_str(alias.as_ref())?;
                        out.write_str(SEP)?;
                    }

                    out.write_str(name.as_ref())?;

                    if !ty.arguments.is_empty() {
                        out.write_str("<")?;

                        let mut it = ty.arguments.iter().peekable();

                        while let Some(argument) = it.next() {
                            argument.format(out, config, level + 1)?;

                            if it.peek().is_some() {
                                out.write_str(", ")?;
                            }
                        }

                        out.write_str(">")?;
                    }
                }
            }
        }

        Ok(())
    }

    fn quote_string(out: &mut Formatter, input: &str) -> fmt::Result {
        out.write_char('"')?;

        for c in input.chars() {
            match c {
                '\t' => out.write_str("\\t")?,
                '\u{0007}' => out.write_str("\\b")?,
                '\n' => out.write_str("\\n")?,
                '\r' => out.write_str("\\r")?,
                '\u{0014}' => out.write_str("\\f")?,
                '\'' => out.write_str("\\'")?,
                '"' => out.write_str("\\\"")?,
                '\\' => out.write_str("\\\\")?,
                c => out.write_char(c)?,
            }
        }

        out.write_char('"')?;

        Ok(())
    }

    fn write_file<'a>(
        tokens: Tokens<'a, Self>,
        out: &mut Formatter,
        config: &mut Self::Config,
        level: usize,
    ) -> fmt::Result {
        let mut toks: Tokens<Self> = Tokens::new();

        toks.push_unless_empty(Self::imports(&tokens, config));
        toks.push_ref(&tokens);
        toks.join_line_spacing().format(out, config, level)
    }
}

/// Setup an imported element.
pub fn imported<'a, P: Into<Cons<'a>>>(path: P) -> Dart<'a> {
    Dart::Type(Type {
        path: Some(path.into()),
        ..Type::default()
    })
}

/// Setup a local element.
pub fn local<'el, N: Into<Cons<'el>>>(name: N) -> Dart<'el> {
    Dart::Type(Type {
        name: Some(name.into()),
        ..Type::default()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dart::Dart;
    use crate::quoted::Quoted;
    use crate::tokens::Tokens;

    #[test]
    fn test_builtin() {
        assert!(INT.is_built_in());
        assert!(DOUBLE.is_built_in());
        assert!(BOOL.is_built_in());
        assert!(!Dart::Void.is_built_in());
    }

    #[test]
    fn test_string() {
        let mut toks: Tokens<Dart> = Tokens::new();
        toks.append("hello \n world".quoted());
        assert_eq!("\"hello \\n world\"", toks.to_string().unwrap().as_str());
    }

    #[test]
    fn test_imported() {
        let import = imported("package:http/http.dart");
        let import2 = imported("package:http/http.dart");
        let import_alias = imported("package:http/http.dart").alias("h2");
        let import_relative = imported("../http.dart");

        let toks = toks![
            import.name("a"),
            import2.name("b"),
            import_alias.name("c"),
            import_relative.name("d"),
        ]
        .join_spacing();

        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!(
            Ok(expected.join("\n").as_str()),
            toks.to_file().as_ref().map(|s| s.as_str())
        );
    }
}