rasn_compiler/
lib.rs

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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#[doc = include_str!("../README.md")]
pub(crate) mod common;
mod generator;
pub mod intermediate;
mod lexer;
#[cfg(test)]
mod tests;
mod validator;

#[cfg(feature = "cli")]
pub mod cli;

use std::{
    cell::RefCell,
    collections::BTreeMap,
    error::Error,
    fs::{self, read_to_string},
    path::PathBuf,
    rc::Rc,
    vec,
};

use generator::Backend;
use intermediate::ToplevelDefinition;
use lexer::asn_spec;
use validator::Validator;

pub mod prelude {
    //! Convenience module that collects all necessary imports for
    //! using and customizing the compiler.
    pub use super::{
        CompileResult, Compiler, CompilerMissingParams, CompilerOutputSet, CompilerReady,
        CompilerSourcesSet,
    };
    pub use crate::generator::{
        error::*,
        rasn::{Config as RasnConfig, Rasn as RasnBackend},
        typescript::{Config as TsConfig, Typescript as TypescriptBackend},
        Backend, GeneratedModule,
    };

    pub use crate::intermediate::{
        ExtensibilityEnvironment, TaggingEnvironment, ToplevelDefinition,
    };

    pub mod ir {
        pub use crate::intermediate::{
            constraints::*,
            encoding_rules::{per_visible::*, *},
            error::*,
            information_object::*,
            parameterization::*,
            types::*,
            *,
        };
    }
}

#[cfg(target_family = "wasm")]
use wasm_bindgen::prelude::*;

#[cfg(target_family = "wasm")]
#[wasm_bindgen(inspectable, getter_with_clone)]
pub struct Generated {
    pub rust: String,
    pub warnings: String,
}

#[cfg(target_family = "wasm")]
#[wasm_bindgen]
pub fn compile_to_typescript(asn1: &str) -> Result<Generated, JsValue> {
    Compiler::<crate::prelude::TypescriptBackend, _>::new()
        .add_asn_literal(asn1)
        .compile_to_string()
        .map(|result| Generated {
            rust: result.generated,
            warnings: result
                .warnings
                .into_iter()
                .fold(String::new(), |mut acc, w| {
                    acc += &w.to_string();
                    acc += "\n";
                    acc
                }),
        })
        .map_err(|e| JsValue::from(e.to_string()))
}

#[cfg(target_family = "wasm")]
#[wasm_bindgen]
pub fn compile_to_rust(
    asn1: &str,
    config: crate::prelude::RasnConfig,
) -> Result<Generated, JsValue> {
    Compiler::<crate::prelude::RasnBackend, _>::new_with_config(config)
        .add_asn_literal(asn1)
        .compile_to_string()
        .map(|result| Generated {
            rust: result.generated,
            warnings: result
                .warnings
                .into_iter()
                .fold(String::new(), |mut acc, w| {
                    acc += &w.to_string();
                    acc += "\n";
                    acc
                }),
        })
        .map_err(|e| JsValue::from(e.to_string()))
}

/// The rasn compiler
pub struct Compiler<B: Backend, S: CompilerState> {
    state: S,
    backend: B,
}

/// Typestate representing compiler with missing parameters
pub struct CompilerMissingParams;

impl Default for CompilerMissingParams {
    fn default() -> Self {
        Self
    }
}

/// Typestate representing compiler that is ready to compile
pub struct CompilerReady {
    sources: Vec<AsnSource>,
    output_path: PathBuf,
}

/// Typestate representing compiler that has the output path set, but is missing ASN1 sources
pub struct CompilerOutputSet {
    output_path: PathBuf,
}

/// Typestate representing compiler that knows about ASN1 sources, but doesn't have an output path set
pub struct CompilerSourcesSet {
    sources: Vec<AsnSource>,
}

/// State of the rasn compiler
pub trait CompilerState {}
impl CompilerState for CompilerReady {}
impl CompilerState for CompilerOutputSet {}
impl CompilerState for CompilerSourcesSet {}
impl CompilerState for CompilerMissingParams {}

#[derive(Debug)]
pub struct CompileResult {
    pub generated: String,
    pub warnings: Vec<Box<dyn Error>>,
}

impl CompileResult {
    fn fmt<B: Backend>(mut self) -> Self {
        self.generated = B::format_bindings(&self.generated).unwrap_or(self.generated);
        self
    }
}

#[derive(Debug, PartialEq)]
enum AsnSource {
    Path(PathBuf),
    Literal(String),
}

impl<B: Backend> Default for Compiler<B, CompilerMissingParams> {
    fn default() -> Self {
        Self::new()
    }
}

impl<B: Backend, S: CompilerState> Compiler<B, S> {
    pub fn with_backend<B2: Backend>(self, backend: B2) -> Compiler<B2, S> {
        Compiler {
            state: self.state,
            backend,
        }
    }
}

impl<B: Backend> Compiler<B, CompilerMissingParams> {
    /// Provides a Builder for building rasn compiler commands
    pub fn new() -> Compiler<B, CompilerMissingParams> {
        Compiler {
            state: CompilerMissingParams,
            backend: B::default(),
        }
    }

    /// Provides a Builder for building rasn compiler commands
    pub fn new_with_config(config: B::Config) -> Compiler<B, CompilerMissingParams> {
        Compiler {
            state: CompilerMissingParams,
            backend: B::from_config(config),
        }
    }
}

impl<B: Backend> Compiler<B, CompilerMissingParams> {
    /// Add an ASN1 source to the compile command by path
    /// * `path_to_source` - path to ASN1 file to include
    pub fn add_asn_by_path(
        self,
        path_to_source: impl Into<PathBuf>,
    ) -> Compiler<B, CompilerSourcesSet> {
        Compiler {
            state: CompilerSourcesSet {
                sources: vec![AsnSource::Path(path_to_source.into())],
            },
            backend: self.backend,
        }
    }

    /// Add several ASN1 sources by path to the compile command
    /// * `path_to_source` - iterator of paths to the ASN1 files to be included
    pub fn add_asn_sources_by_path(
        self,
        paths_to_sources: impl Iterator<Item = impl Into<PathBuf>>,
    ) -> Compiler<B, CompilerSourcesSet> {
        Compiler {
            state: CompilerSourcesSet {
                sources: paths_to_sources
                    .map(|p| AsnSource::Path(p.into()))
                    .collect(),
            },
            backend: self.backend,
        }
    }

    /// Add a literal ASN1 source to the compile command
    /// * `literal` - literal ASN1 statement to include
    /// ```rust
    /// # use rasn_compiler::prelude::*;
    /// Compiler::<RasnBackend, _>::new().add_asn_literal(format!(
    ///     "TestModule DEFINITIONS AUTOMATIC TAGS::= BEGIN {} END",
    ///     "My-test-integer ::= INTEGER (1..128)"
    /// )).compile_to_string();
    /// ```
    pub fn add_asn_literal(self, literal: impl Into<String>) -> Compiler<B, CompilerSourcesSet> {
        Compiler {
            state: CompilerSourcesSet {
                sources: vec![AsnSource::Literal(literal.into())],
            },
            backend: self.backend,
        }
    }

    /// Set the output path for the generated rust representation.
    /// * `output_path` - path to an output file or directory, if path indicates
    ///                   a directory, the output file is named `rasn_generated.rs`
    pub fn set_output_path(
        self,
        output_path: impl Into<PathBuf>,
    ) -> Compiler<B, CompilerOutputSet> {
        let mut path: PathBuf = output_path.into();
        if path.is_dir() {
            path.set_file_name("rasn_generated.rs");
        }
        Compiler {
            state: CompilerOutputSet { output_path: path },
            backend: self.backend,
        }
    }
}

impl<B: Backend> Compiler<B, CompilerOutputSet> {
    /// Add an ASN1 source to the compile command by path
    /// * `path_to_source` - path to ASN1 file to include
    pub fn add_asn_by_path(self, path_to_source: impl Into<PathBuf>) -> Compiler<B, CompilerReady> {
        Compiler {
            state: CompilerReady {
                sources: vec![AsnSource::Path(path_to_source.into())],
                output_path: self.state.output_path,
            },
            backend: self.backend,
        }
    }

    /// Add several ASN1 sources by path to the compile command
    /// * `path_to_source` - iterator of paths to the ASN1 files to be included
    pub fn add_asn_sources_by_path(
        self,
        paths_to_sources: impl Iterator<Item = impl Into<PathBuf>>,
    ) -> Compiler<B, CompilerReady> {
        Compiler {
            state: CompilerReady {
                sources: paths_to_sources
                    .map(|p| AsnSource::Path(p.into()))
                    .collect(),
                output_path: self.state.output_path,
            },
            backend: self.backend,
        }
    }

    /// Add a literal ASN1 source to the compile command
    /// * `literal` - literal ASN1 statement to include
    /// ```rust
    /// # use rasn_compiler::prelude::*;
    /// Compiler::<RasnBackend, _>::new().add_asn_literal(format!(
    ///     "TestModule DEFINITIONS AUTOMATIC TAGS::= BEGIN {} END",
    ///     "My-test-integer ::= INTEGER (1..128)"
    /// )).compile_to_string();
    /// ```
    pub fn add_asn_literal(self, literal: impl Into<String>) -> Compiler<B, CompilerReady> {
        Compiler {
            state: CompilerReady {
                sources: vec![AsnSource::Literal(literal.into())],
                output_path: self.state.output_path,
            },
            backend: self.backend,
        }
    }
}

impl<B: Backend> Compiler<B, CompilerSourcesSet> {
    /// Add an ASN1 source to the compile command by path
    /// * `path_to_source` - path to ASN1 file to include
    pub fn add_asn_by_path(
        self,
        path_to_source: impl Into<PathBuf>,
    ) -> Compiler<B, CompilerSourcesSet> {
        let mut sources: Vec<AsnSource> = self.state.sources;
        sources.push(AsnSource::Path(path_to_source.into()));
        Compiler {
            state: CompilerSourcesSet { sources },
            backend: self.backend,
        }
    }

    /// Add several ASN1 sources by path to the compile command
    /// * `path_to_source` - iterator of paths to the ASN1 files to be included
    pub fn add_asn_sources_by_path(
        self,
        paths_to_sources: impl Iterator<Item = impl Into<PathBuf>>,
    ) -> Compiler<B, CompilerSourcesSet> {
        let mut sources: Vec<AsnSource> = self.state.sources;
        sources.extend(paths_to_sources.map(|p| AsnSource::Path(p.into())));
        Compiler {
            state: CompilerSourcesSet { sources },
            backend: self.backend,
        }
    }

    /// Add a literal ASN1 source to the compile command
    /// * `literal` - literal ASN1 statement to include
    /// ```rust
    /// # use rasn_compiler::prelude::*;
    /// Compiler::<RasnBackend, _>::new().add_asn_literal(format!(
    ///     "TestModule DEFINITIONS AUTOMATIC TAGS::= BEGIN {} END",
    ///     "My-test-integer ::= INTEGER (1..128)"
    /// )).compile_to_string();
    /// ```
    pub fn add_asn_literal(self, literal: impl Into<String>) -> Compiler<B, CompilerSourcesSet> {
        let mut sources: Vec<AsnSource> = self.state.sources;
        sources.push(AsnSource::Literal(literal.into()));
        Compiler {
            state: CompilerSourcesSet { sources },
            backend: self.backend,
        }
    }

    /// Set the output path for the generated rust representation.
    /// * `output_path` - path to an output file or directory, if path points to
    ///                   a directory, the compiler will generate a file for every ASN.1 module.
    ///                   If the path points to a file, all modules will be written to that file.
    pub fn set_output_path(self, output_path: impl Into<PathBuf>) -> Compiler<B, CompilerReady> {
        Compiler {
            state: CompilerReady {
                sources: self.state.sources,
                output_path: output_path.into(),
            },
            backend: self.backend,
        }
    }

    /// Runs the rasn compiler command and returns stringified Rust.
    /// Returns a Result wrapping a compilation result:
    /// * _Ok_  - tuple containing the stringified bindings for the ASN1 spec as well as a vector of warnings raised during the compilation
    /// * _Err_ - Unrecoverable error, no rust representations were generated
    pub fn compile_to_string(mut self) -> Result<CompileResult, Box<dyn Error>> {
        self.internal_compile().map(CompileResult::fmt::<B>)
    }

    fn internal_compile(&mut self) -> Result<CompileResult, Box<dyn Error>> {
        let mut generated_modules = vec![];
        let mut warnings = Vec::<Box<dyn Error>>::new();
        let mut modules: Vec<ToplevelDefinition> = vec![];
        for src in &self.state.sources {
            let stringified_src = match src {
                AsnSource::Path(p) => read_to_string(p)?,
                AsnSource::Literal(l) => l.clone(),
            };
            modules.append(
                &mut asn_spec(&stringified_src)?
                    .into_iter()
                    .flat_map(|(header, tlds)| {
                        let header_ref = Rc::new(RefCell::new(header));
                        tlds.into_iter().enumerate().map(move |(index, mut tld)| {
                            tld.apply_tagging_environment(&header_ref.borrow().tagging_environment);
                            tld.set_index(header_ref.clone(), index);
                            tld
                        })
                    })
                    .collect(),
            );
        }
        let (valid_items, mut validator_errors) = Validator::new(modules).validate()?;
        let modules = valid_items.into_iter().fold(
            BTreeMap::<String, Vec<ToplevelDefinition>>::new(),
            |mut modules, tld| {
                let key = tld
                    .get_index()
                    .map_or(<_>::default(), |(module, _)| module.borrow().name.clone());
                match modules.entry(key) {
                    std::collections::btree_map::Entry::Vacant(v) => {
                        v.insert(vec![tld]);
                    }
                    std::collections::btree_map::Entry::Occupied(ref mut e) => {
                        e.get_mut().push(tld)
                    }
                }
                modules
            },
        );
        for (_, module) in modules {
            let mut generated_module = self.backend.generate_module(module)?;
            if let Some(m) = generated_module.generated {
                generated_modules.push(m);
            }
            warnings.append(&mut generated_module.warnings);
        }
        warnings.append(&mut validator_errors);

        Ok(CompileResult {
            generated: generated_modules.join("\n"),
            warnings,
        })
    }
}

impl<B: Backend> Compiler<B, CompilerReady> {
    /// Add an ASN1 source to the compile command by path
    /// * `path_to_source` - path to ASN1 file to include
    pub fn add_asn_by_path(self, path_to_source: impl Into<PathBuf>) -> Compiler<B, CompilerReady> {
        let mut sources: Vec<AsnSource> = self.state.sources;
        sources.push(AsnSource::Path(path_to_source.into()));
        Compiler {
            state: CompilerReady {
                output_path: self.state.output_path,
                sources,
            },
            backend: self.backend,
        }
    }

    /// Add several ASN1 sources by path to the compile command
    /// * `path_to_source` - iterator of paths to the ASN1 files to be included
    pub fn add_asn_sources_by_path(
        self,
        paths_to_sources: impl Iterator<Item = impl Into<PathBuf>>,
    ) -> Compiler<B, CompilerReady> {
        let mut sources: Vec<AsnSource> = self.state.sources;
        sources.extend(paths_to_sources.map(|p| AsnSource::Path(p.into())));
        Compiler {
            state: CompilerReady {
                sources,
                output_path: self.state.output_path,
            },
            backend: self.backend,
        }
    }

    /// Add a literal ASN1 source to the compile command
    /// * `literal` - literal ASN1 statement to include
    /// ```rust
    /// # use rasn_compiler::prelude::*;
    /// Compiler::<RasnBackend, _>::new().add_asn_literal(format!(
    ///     "TestModule DEFINITIONS AUTOMATIC TAGS::= BEGIN {} END",
    ///     "My-test-integer ::= INTEGER (1..128)"
    /// )).compile_to_string();
    /// ```
    pub fn add_asn_literal(self, literal: impl Into<String>) -> Compiler<B, CompilerReady> {
        let mut sources: Vec<AsnSource> = self.state.sources;
        sources.push(AsnSource::Literal(literal.into()));
        Compiler {
            state: CompilerReady {
                output_path: self.state.output_path,
                sources,
            },
            backend: self.backend,
        }
    }

    /// Runs the rasn compiler command and returns stringified Rust.
    /// Returns a Result wrapping a compilation result:
    /// * _Ok_  - tuple containing the stringified bindings for the ASN1 spec as well as a vector of warnings raised during the compilation
    /// * _Err_ - Unrecoverable error, no rust representations were generated
    pub fn compile_to_string(self) -> Result<CompileResult, Box<dyn Error>> {
        Compiler {
            state: CompilerSourcesSet {
                sources: self.state.sources,
            },
            backend: self.backend,
        }
        .compile_to_string()
    }

    /// Runs the rasn compiler command.
    /// Returns a Result wrapping a compilation result:
    /// * _Ok_  - Vector of warnings raised during the compilation
    /// * _Err_ - Unrecoverable error, no rust representations were generated
    pub fn compile(self) -> Result<Vec<Box<dyn Error>>, Box<dyn Error>> {
        let result = Compiler {
            state: CompilerSourcesSet {
                sources: self.state.sources,
            },
            backend: self.backend,
        }
        .internal_compile()?
        .fmt::<B>();
        fs::write(
            self.state
                .output_path
                .is_dir()
                .then(|| {
                    self.state
                        .output_path
                        .join(format!("generated{}", B::FILE_EXTENSION))
                })
                .unwrap_or(self.state.output_path),
            result.generated,
        )?;

        Ok(result.warnings)
    }
}