aboutsummaryrefslogtreecommitdiff
path: root/apps/cassiopeia/src/format/mod.rs
blob: 814c08656dbe0ca8d11f4eb27853d0603a643457 (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
//! cassiopeia file format

mod ir;
mod lexer;
mod parser;

pub(crate) use ir::{IrItem, IrStream, IrType, MakeIr};
pub(crate) use lexer::{LineLexer, LineToken, Token};
pub(crate) use parser::LineCfg;

use crate::TimeFile;
use std::{fs::File, io::Read};

#[derive(Default)]
pub struct ParseOutput {
    pub(crate) ir: IrStream,
    pub(crate) tf: TimeFile,
}

impl ParseOutput {
    fn append(mut self, ir: IrItem) -> Self {
        self.tf.append(ir.clone());
        self.ir.push(ir);
        self
    }
}

/// Load a file from disk and parse it into a
/// [`TimeFile`](crate::TimeFile)
pub fn load_file(path: &str) -> Option<ParseOutput> {
    let mut f = File::open(path).ok()?;
    let mut content = String::new();
    f.read_to_string(&mut content).ok()?;

    let mut lines: Vec<String> = content.split("\n").map(|l| l.to_owned()).collect();

    Some(
        ir::generate_ir(
            lines
                .iter_mut()
                .map(|line| lexer::lex(line))
                .map(|lex| parser::parse(lex)),
        )
        .into_iter()
        .fold(ParseOutput::default(), |output, ir| output.append(ir)),
    )
}