specta-elm 0.0.1

Yey! now your Rust types in Elm ;)
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
use std::{
    collections::{HashMap, HashSet},
    fmt::{self, Debug},
    fs::File,
    io::BufReader,
    path::{Path, PathBuf},
};

use serde_json::Value;
use specta::{
    Types,
    datatype::{DataType, Fields, NamedDataType},
};

use crate::{
    Error,
    export::{Exporter, IntoExporter},
};

// Constants {{{
pub(crate) const COMMENT_SYMBOL: &'static str = "-- ";
pub(crate) const EXTENSION: &'static str = "elm";
pub(crate) const ELM_ENUM_SYMBOL: &'static str = "type ";
pub(crate) const ELM_STRUCT_SYMBOL: &'static str = "type alias ";
pub(crate) const PRELUDE: &'static str = "generated by specta-elm";
pub(crate) const RESERVED_TYPE_NAMES: &[&str] = &[
    "if", "then", "else", "case", "of", "let", "in", "type", "module", "where", "import",
    "exposing", "as", "port",
];
// }}}
// Types {{{
fn recurse_fields(fields: &Fields) {
    match fields {
        specta::datatype::Fields::Unit => (),
        specta::datatype::Fields::Unnamed(unnamed_fields) => {
            for field in unnamed_fields.fields.iter() {
                if let Some(dt) = &field.ty {
                    recurse_dt_and_panic(&dt);
                }
            }
        }
        specta::datatype::Fields::Named(named_fields) => {
            for (_, field) in named_fields.fields.iter() {
                if let Some(dt) = &field.ty {
                    recurse_dt_and_panic(&dt);
                }
            }
        }
    }
}
fn recurse_dt_and_panic(dt: &DataType) {
    match dt {
        DataType::List(list) => recurse_dt_and_panic(&list.ty),
        DataType::Map(map) => {
            recurse_dt_and_panic(map.key_ty());
            recurse_dt_and_panic(map.value_ty());
        }
        DataType::Struct(st) => recurse_fields(&st.fields),
        DataType::Enum(en) => {
            for (_, variant) in &en.variants {
                recurse_fields(&variant.fields);
            }
        }
        DataType::Tuple(tuple) => {
            for dt in &tuple.elements {
                recurse_dt_and_panic(&dt);
            }
        }
        DataType::Nullable(data_type) => recurse_dt_and_panic(&data_type),
        DataType::Intersection(data_types) => {
            for dt in data_types {
                recurse_dt_and_panic(&dt);
            }
        }
        DataType::Reference(reference) => match reference {
            specta::datatype::Reference::Named(named_reference) => {
                match &named_reference.inner {
                    specta::datatype::NamedReferenceType::Recursive(_recursive_inline_type) => {
                        panic!("recursivity")
                    }
                    specta::datatype::NamedReferenceType::Inline { dt, .. } => {
                        recurse_dt_and_panic(&dt)
                    }
                    specta::datatype::NamedReferenceType::Reference { generics, .. } => {
                        if !generics.is_empty() {
                            panic!("generics")
                        }
                    }
                };
            }
            specta::datatype::Reference::Opaque(_opaque_reference) => panic!("opaque ref"),
        },
        DataType::Generic(_generic) => panic!("generic"),
        _ => (),
    }
}
fn guard_panic_on_unsupported_types<'a>(types: &Types) {
    for ndt in types.into_unsorted_iter() {
        if ndt.name.is_empty() {
            panic!("unnamed")
        }

        if let Some(dt) = &ndt.ty {
            recurse_dt_and_panic(&dt);
        }
    }
}
//
// }}}
// Elm {{{

#[derive(Debug, Clone)]
// #[non_exhaustive]
// pub struct Elm<E: Exporter> {
pub struct Elm {
    project: Project,
    // exporter: E,
    types: Types,
}

// impl<E: Exporter> Elm<E> {
impl Elm {
    pub fn init(types: Types, path: &str) -> Self {
        guard_panic_on_unsupported_types(&types);
        let project = Project::try_from(path).expect("no elm.json in path or path chidren");
        Elm { project, types }
        // let exporter = IntoExporter::into(output, &project);

        // Elm { exporter, project }
    }

    pub fn export<E: Exporter, O: IntoExporter<Output = E>>(
        &mut self,
        output: O,
    ) -> Result<(), Error> {
        let mut exporter = output.into(&self.project);
        exporter.export(&self.types);
        self.project.cleanup_stale_files()
    }
}

#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum ElmCoreLibImport {
    Dict,
    Set,
}

impl fmt::Display for ElmCoreLibImport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            ElmCoreLibImport::Dict => "Dict",
            ElmCoreLibImport::Set => "Set",
        })
    }
}

// }}}
// Project {{{
#[derive(Debug, Clone)]
pub struct Project {
    src_dirs: Vec<PathBuf>,
    // config: Value,
}

impl Project {
    pub fn source_directories(&self) -> &[PathBuf] {
        self.src_dirs.as_slice()
    }
    fn cleanup_stale_files(&mut self) -> Result<(), Error> {
        for dir in &self.src_dirs {
            if dir.exists() {
                return Ok(());
            }
        }

        for dir in &self.src_dirs {
            for path in collect_existing_files(dir)? {
                if !is_generated_specta_file(&path)? {
                    continue;
                }

                std::fs::remove_file(&path).or_else(|source| {
                    if source.kind() == std::io::ErrorKind::NotFound {
                        Ok(())
                    } else {
                        Err(Error::remove_file(path.clone(), source))
                    }
                })?;
            }
            remove_empty_dirs(dir, dir)?;
        }

        Ok(())
    }
}

impl TryFrom<&str> for Project {
    type Error = Error;

    fn try_from(path: &str) -> Result<Self, Self::Error> {
        let path = PathBuf::from(path);

        let start: PathBuf = if path.is_file() {
            path.parent()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| PathBuf::from("."))
        } else {
            path
        };

        let elm_json_path = search_down(&start, 2).expect("couldn't find elm.json file");

        let file =
            File::open(&elm_json_path).map_err(|e| Error::read_file(elm_json_path.clone(), e))?;

        let config: Value =
            serde_json::from_reader(BufReader::new(file)).expect("couldn't deserialize elm.json");

        let src_dirs = config
            .get("source-directories")
            .and_then(Value::as_array)
            .map(|arr| {
                arr.iter()
                    .filter_map(Value::as_str)
                    .map(|rel_dir| {
                        PathBuf::from(
                            elm_json_path
                                .parent()
                                .expect("elm project is batman (somehow elm.json exists butt no parent :l)")
                                .join(rel_dir),
                        )
                    })
                    .collect()
            })
            .unwrap_or_default();

        // Ok(Project { src_dirs, config })
        Ok(Project { src_dirs })
    }
}

fn search_down(root: &Path, max_depth: usize) -> Option<PathBuf> {
    let candidate = root.join("elm.json");
    if candidate.is_file() {
        return Some(candidate);
    }
    if max_depth == 0 {
        return None;
    }
    let entries = std::fs::read_dir(root).ok()?;
    for entry in entries.filter_map(Result::ok) {
        let entry_path = entry.path();
        if entry_path.is_dir() {
            if let Some(found) = search_down(&entry_path, max_depth - 1) {
                return Some(found);
            }
        }
    }
    None
}

// }}}
// References {{{
pub type ReferenceExports = HashMap<String, NamedDataType>;

// #[derive(Default, Debug)]
// pub struct References<'a> {
//     pool: HashSet<&'a NamedReference>,
// }
//
// impl<'a> References<'a> {
//     pub fn collect(types: &'a Types) -> Self {
//         let mut refs = References::default();
//
//         for ndt in types.into_sorted_iter() {
//             if let Some(dt) = &ndt.ty {
//                 refs.collect_refs(&dt);
//                 // refs.exports.insert(ndt.name.to_string(), ndt.clone());
//             }
//         }
//
//         refs
//     }
//
//     fn collect_fields(&mut self, fields: &'a Fields) {
//         match fields {
//             Fields::Unit => {}
//             Fields::Unnamed(u) => {
//                 for f in &u.fields {
//                     if let Some(ty) = &f.ty {
//                         self.collect_refs(ty);
//                     }
//                 }
//                 panic!("unnamed fields are not supported in Elm");
//             }
//             Fields::Named(n) => {
//                 for (_, f) in &n.fields {
//                     if let Some(ty) = &f.ty {
//                         eprintln!("field export: {:?}", ty);
//                         self.collect_refs(ty);
//                     }
//                 }
//             }
//         }
//     }
//
//     fn collect_refs(&mut self, dt: &'a DataType) {
//         match dt {
//             DataType::Primitive(_) | DataType::Generic(_) => {}
//
//             DataType::List(list) => self.collect_refs(&list.ty),
//
//             DataType::Map(map) => {
//                 self.collect_refs(map.key_ty());
//                 self.collect_refs(map.value_ty());
//             }
//
//             DataType::Tuple(tuple) => {
//                 for ty in &tuple.elements {
//                     self.collect_refs(ty);
//                 }
//             }
//
//             DataType::Nullable(inner) => self.collect_refs(inner),
//
//             DataType::Intersection(types) => {
//                 for t in types {
//                     self.collect_refs(t);
//                 }
//             }
//
//             DataType::Struct(s) => self.collect_fields(&s.fields),
//
//             DataType::Enum(e) => {
//                 for (_, variant) in &e.variants {
//                     self.collect_fields(&variant.fields);
//                 }
//             }
//
//             DataType::Reference(reference) => match reference {
//                 Reference::Named(nref) => match &nref.inner {
//                     // stdlib "named" wrappers around primitives (String, CString, OsString, ...)
//                     // aren't real declarations — recurse into the inline body and don't pool them.
//                     NamedReferenceType::Inline { dt, .. } => self.collect_refs(dt),
//                     NamedReferenceType::Reference { generics, .. } => {
//                         // panic!("Elm don't like generics");
//                         // self.pool.insert(nref);
//                         if !generics.is_empty() {
//                             panic!("NO GENERICSS!!");
//                         }
//                     }
//                     NamedReferenceType::Recursive(_) => {
//                         panic!("dont recurseee!!")
//                         // self.pool.insert(nref);
//                     }
//                 },
//                 Reference::Opaque(_) => panic!("we don't like opaque refs"),
//             },
//         }
//     }
// }
//
// }}}
// Utils: file managing {{{
fn collect_existing_files(root: &Path) -> Result<HashSet<PathBuf>, Error> {
    if !root.exists() {
        return Ok(HashSet::new());
    }

    let mut files = HashSet::new();
    let entries =
        std::fs::read_dir(root).map_err(|source| Error::read_dir(root.to_path_buf(), source))?;
    for entry in entries {
        let entry = entry.map_err(|source| Error::read_dir(root.to_path_buf(), source))?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .map_err(|source| Error::metadata(path.clone(), source))?;

        if file_type.is_symlink() {
            continue;
        }

        if file_type.is_dir() {
            files.extend(collect_existing_files(&path)?);
        } else if matches!(path.extension().and_then(|e| e.to_str()), Some(EXTENSION)) {
            files.insert(path);
        }
    }

    Ok(files)
}

fn is_generated_specta_file(path: &Path) -> Result<bool, Error> {
    match std::fs::read_to_string(path) {
        Ok(contents) => {
            Ok((contents.contains("generated by Specta")) || contents.contains(PRELUDE))
        }
        Err(err) if err.kind() == std::io::ErrorKind::InvalidData => Ok(false),
        Err(source) => Err(Error::read_file(path.to_path_buf(), source)),
    }
}

/// Remove empty directories recursively, stopping at the root
fn remove_empty_dirs(path: &Path, root: &Path) -> Result<(), Error> {
    let entries =
        std::fs::read_dir(path).map_err(|source| Error::read_dir(path.to_path_buf(), source))?;
    for entry in entries {
        let entry = entry.map_err(|source| Error::read_dir(path.to_path_buf(), source))?;
        let entry_path = entry.path();
        let file_type = entry
            .file_type()
            .map_err(|source| Error::metadata(entry_path.clone(), source))?;
        if file_type.is_symlink() {
            continue;
        }
        if file_type.is_dir() {
            remove_empty_dirs(&entry_path, root)?;
        }
    }

    let is_empty = path
        .read_dir()
        .map_err(|source| Error::read_dir(path.to_path_buf(), source))?
        .next()
        .is_none();

    if path != root && is_empty {
        match std::fs::remove_dir(path) {
            Ok(()) => {}
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(source) => {
                return Err(Error::remove_dir(path.to_path_buf(), source));
            }
        }
    }
    Ok(())
}

// }}}