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
//! Specialization for Java code generation.
//!
//! # String Quoting in Java
//!
//! 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: java::Tokens = quote!("start π 😊 \n \x7f end");
//! assert_eq!("\"start \\u03c0 \\ud83d\\ude0a \\n \\u007f end\"", toks.to_string()?);
//! # Ok(())
//! # }
//! ```

mod block_comment;

pub use self::block_comment::BlockComment;

use crate as genco;
use crate::fmt;
use crate::tokens::ItemStr;
use crate::{quote, quote_in};
use std::collections::{BTreeSet, HashMap};
use std::fmt::Write as _;

/// Tokens container specialized for Java.
pub type Tokens = crate::Tokens<Java>;

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

        fn write_quoted(out: &mut fmt::Formatter<'_>, input: &str) -> fmt::Result {
            // From: https://docs.oracle.com/javase/tutorial/java/data/characters.html
            use std::fmt::Write as _;

            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("\\\\")?,
                    ' ' => out.write_char(' ')?,
                    c if c.is_ascii() && !c.is_control() => out.write_char(c)?,
                    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 header = Tokens::new();

            if let Some(ref package) = config.package {
                quote_in!(header => package $package;);
                header.line();
            }

            let mut format = Format::default();
            Self::imports(&mut header, tokens, config, &mut format.imported);
            header.format(out, config, &format)?;
            tokens.format(out, config, &format)?;
            Ok(())
        }
    }

    Import {
        fn format(&self, out: &mut fmt::Formatter<'_>, config: &Config, format: &Format) -> fmt::Result {
            let file_package = config.package.as_ref().map(|p| p.as_ref());
            let imported = format.imported.get(self.name.as_ref()).map(String::as_str);
            let pkg = Some(self.package.as_ref());

            if &*self.package != JAVA_LANG && imported != pkg && file_package != pkg {
                out.write_str(self.package.as_ref())?;
                out.write_str(SEP)?;
            }

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

const JAVA_LANG: &str = "java.lang";
const SEP: &str = ".";

/// Formtat state for Java.
#[derive(Debug, Default)]
pub struct Format {
    /// Types which has been imported into the local namespace.
    imported: HashMap<String, String>,
}

/// Configuration for Java.
#[derive(Debug, Default)]
pub struct Config {
    /// Package to use.
    package: Option<ItemStr>,
}

impl Config {
    /// Configure package to use for the file generated.
    ///
    /// # Examples
    ///
    /// ```
    /// use genco::prelude::*;
    /// use genco::fmt;
    ///
    /// let optional = java::import("java.util", "Optional");
    ///
    /// let toks = quote!($optional);
    ///
    /// let config = java::Config::default().with_package("java.util");
    /// let fmt = fmt::Config::from_lang::<Java>();
    ///
    /// let mut w = fmt::VecWriter::new();
    ///
    /// toks.format_file(&mut w.as_formatter(&fmt), &config)?;
    ///
    /// assert_eq!(
    ///     vec![
    ///         "package java.util;",
    ///         "",
    ///         "Optional",
    ///     ],
    ///     w.into_vec(),
    /// );
    /// # Ok::<_, genco::fmt::Error>(())
    /// ```
    pub fn with_package<P>(self, package: P) -> Self
    where
        P: Into<ItemStr>,
    {
        Self {
            package: Some(package.into()),
        }
    }
}

/// The import of a Java type `import java.util.Optional;`.
///
/// Created through the [import()] function.
#[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Import {
    /// Package of the class.
    package: ItemStr,
    /// Name  of class.
    name: ItemStr,
}

impl Java {
    fn imports(
        out: &mut Tokens,
        tokens: &Tokens,
        config: &Config,
        imported: &mut HashMap<String, String>,
    ) {
        let mut modules = BTreeSet::new();

        let file_package = config.package.as_ref().map(|p| p.as_ref());

        for import in tokens.walk_imports() {
            modules.insert((import.package.clone(), import.name.clone()));
        }

        if modules.is_empty() {
            return;
        }

        for (package, name) in modules {
            if imported.contains_key(&*name) {
                continue;
            }

            if &*package == JAVA_LANG {
                continue;
            }

            if Some(&*package) == file_package {
                continue;
            }

            out.append(quote!(import $(package.clone())$(SEP)$(name.clone());));
            out.push();

            imported.insert(name.to_string(), package.to_string());
        }

        out.line();
    }
}

/// The import of a Java type `import java.util.Optional;`.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let integer = java::import("java.lang", "Integer");
/// let a = java::import("java.io", "A");
///
/// let toks = quote! {
///     $integer
///     $a
/// };
///
/// assert_eq!(
///     vec![
///         "import java.io.A;",
///         "",
///         "Integer",
///         "A",
///     ],
///     toks.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn import<P, N>(package: P, name: N) -> Import
where
    P: Into<ItemStr>,
    N: Into<ItemStr>,
{
    Import {
        package: package.into(),
        name: name.into(),
    }
}

/// Format a block comment, starting with `/**`, and ending in `*/`.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
/// use std::iter;
///
/// let toks = quote! {
///     $(java::block_comment(vec!["first line", "second line"]))
///     $(java::block_comment(iter::empty::<&str>()))
///     $(java::block_comment(vec!["third line"]))
/// };
///
/// assert_eq!(
///     vec![
///         "/**",
///         " * first line",
///         " * second line",
///         " */",
///         "/**",
///         " * third line",
///         " */",
///     ],
///     toks.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn block_comment<T>(comment: T) -> BlockComment<T>
where
    T: IntoIterator,
    T::Item: Into<ItemStr>,
{
    BlockComment(comment)
}