aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 8992d29c4a6c87d57c34c0a95585b932103f64df (plain)
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
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! PDL parser and analyzer.

use argh::FromArgs;
use codespan_reporting::term::{self, termcolor};

use pdl_compiler::{analyzer, ast, backends, parser};

#[allow(clippy::upper_case_acronyms)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum OutputFormat {
    JSON,
    Rust,
    RustNoAlloc,
    RustNoAllocTest,
}

impl std::str::FromStr for OutputFormat {
    type Err = String;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input.to_lowercase().as_str() {
            "json" => Ok(Self::JSON),
            "rust" => Ok(Self::Rust),
            "rust_no_alloc" => Ok(Self::RustNoAlloc),
            "rust_no_alloc_test" => Ok(Self::RustNoAllocTest),
            _ => Err(format!("could not parse {:?}, valid option are 'json', 'rust', 'rust_no_alloc', and 'rust_no_alloc_test'.", input)),
        }
    }
}

#[derive(FromArgs, Debug)]
/// PDL analyzer and generator.
struct Opt {
    #[argh(switch)]
    /// print tool version and exit.
    version: bool,

    #[argh(option, default = "OutputFormat::JSON")]
    /// generate output in this format ("json", "rust", "rust_no_alloc", "rust_no_alloc_test"). The output
    /// will be printed on stdout in both cases.
    output_format: OutputFormat,

    #[argh(positional)]
    /// input file.
    input_file: String,

    #[argh(option)]
    /// exclude declarations from the generated output.
    exclude_declaration: Vec<String>,
}

/// Remove declarations listed in the input filter.
fn filter_declarations(
    file: parser::ast::File,
    exclude_declarations: &[String],
) -> parser::ast::File {
    ast::File {
        declarations: file
            .declarations
            .into_iter()
            .filter(|decl| {
                decl.id().map(|id| !exclude_declarations.contains(&id.to_owned())).unwrap_or(true)
            })
            .collect(),
        ..file
    }
}

fn main() -> Result<(), String> {
    let opt: Opt = argh::from_env();

    if opt.version {
        println!("Packet Description Language parser version 1.0");
        return Ok(());
    }

    let mut sources = ast::SourceDatabase::new();
    match parser::parse_file(&mut sources, &opt.input_file) {
        Ok(file) => {
            let file = filter_declarations(file, &opt.exclude_declaration);
            let analyzed_file = match analyzer::analyze(&file) {
                Ok(file) => file,
                Err(diagnostics) => {
                    diagnostics
                        .emit(
                            &sources,
                            &mut termcolor::StandardStream::stderr(termcolor::ColorChoice::Always)
                                .lock(),
                        )
                        .expect("Could not print analyzer diagnostics");
                    return Err(String::from("Analysis failed"));
                }
            };

            match opt.output_format {
                OutputFormat::JSON => {
                    println!("{}", backends::json::generate(&file).unwrap())
                }
                OutputFormat::Rust => {
                    println!("{}", backends::rust::generate(&sources, &analyzed_file))
                }
                OutputFormat::RustNoAlloc => {
                    let schema = backends::intermediate::generate(&file).unwrap();
                    println!("{}", backends::rust_no_allocation::generate(&file, &schema).unwrap())
                }
                OutputFormat::RustNoAllocTest => {
                    println!(
                        "{}",
                        backends::rust_no_allocation::test::generate_test_file().unwrap()
                    )
                }
            }
            Ok(())
        }

        Err(err) => {
            let writer = termcolor::StandardStream::stderr(termcolor::ColorChoice::Always);
            let config = term::Config::default();
            term::emit(&mut writer.lock(), &config, &sources, &err).expect("Could not print error");
            Err(String::from("Error while parsing input"))
        }
    }
}