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
use std::{path::PathBuf, time::Instant};

use anyhow::Result;
use ariadne::{sources, Source};
use clap::Parser;
use edlang_ast::Module;
use edlang_lowering::lower_modules;
use edlang_session::{DebugInfo, OptLevel, Session};

use crate::linker::{link_binary, link_shared_lib};

pub mod linker;

#[derive(Parser, Debug)]
#[command(author, version, about = "edlang compiler driver", long_about = None, bin_name = "edlangc")]
pub struct CompilerArgs {
    /// The input file.
    pub input: PathBuf,

    /// The output file.
    pub output: PathBuf,

    /// Build for release with all optimizations.
    #[arg(short, long, default_value_t = false)]
    pub release: bool,

    /// Set the optimization level, 0,1,2,3
    #[arg(short = 'O', long)]
    pub optlevel: Option<u8>,

    /// Always add debug info
    #[arg(long)]
    pub debug_info: Option<bool>,

    /// Build as a library.
    #[arg(short, long, default_value_t = false)]
    pub library: bool,

    /// Print the edlang AST
    #[arg(long, default_value_t = false)]
    pub ast: bool,

    /// Print the edlang IR
    #[arg(long, default_value_t = false)]
    pub ir: bool,

    /// Output llvm ir
    #[arg(long, default_value_t = false)]
    pub llvm: bool,

    /// Output asm
    #[arg(long, default_value_t = false)]
    pub asm: bool,

    /// Output a object file
    #[arg(long, default_value_t = false)]
    pub object: bool,
}

pub fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    let args = CompilerArgs::parse();

    let object = compile(&args)?;

    if args.library {
        link_shared_lib(&[object.clone()], &args.output)?;
    } else {
        link_binary(&[object.clone()], &args.output)?;
    }

    if !args.object {
        std::fs::remove_file(object)?;
    }

    Ok(())
}

pub fn parse_file(modules: &mut Vec<(PathBuf, String, Module)>, mut path: PathBuf) -> Result<()> {
    if path.is_dir() {
        path = path.join("mod.ed");
    }

    let source = std::fs::read_to_string(&path)?;

    let module_ast = edlang_parser::parse_ast(
        &source,
        &path.file_stem().expect("no file stem").to_string_lossy(),
    );

    let module_temp = match module_ast {
        Ok(module) => module,
        Err(error) => {
            let path = path.display().to_string();
            let report = edlang_parser::error_to_report(&path, &error)?;
            edlang_parser::print_report(&path, &source, report)?;
            std::process::exit(1)
        }
    };

    for ident in &module_temp.external_modules {
        let module_path = path
            .parent()
            .unwrap()
            .join(&ident.name)
            .with_extension("ed");
        // todo: fancy error if doesnt exist?
        parse_file(modules, module_path)?;
    }

    modules.push((path, source, module_temp));

    Ok(())
}

pub fn compile(args: &CompilerArgs) -> Result<PathBuf> {
    let start_time = Instant::now();

    let mut modules = Vec::new();
    parse_file(&mut modules, args.input.clone())?;

    let session = Session {
        file_paths: modules.iter().map(|x| x.0.clone()).collect(),
        debug_info: if let Some(debug_info) = args.debug_info {
            if debug_info {
                DebugInfo::Full
            } else {
                DebugInfo::None
            }
        } else if args.release {
            DebugInfo::None
        } else {
            DebugInfo::Full
        },
        optlevel: if let Some(optlevel) = args.optlevel {
            match optlevel {
                0 => OptLevel::None,
                1 => OptLevel::Less,
                2 => OptLevel::Default,
                _ => OptLevel::Aggressive,
            }
        } else if args.release {
            OptLevel::Aggressive
        } else {
            OptLevel::None
        },
        sources: modules.iter().map(|x| Source::from(x.1.clone())).collect(),
        library: args.library,
        output_file: args.output.with_extension("o"),
        output_asm: args.asm,
        output_llvm: args.llvm,
    };
    tracing::debug!("Output file: {:#?}", session.output_file);
    tracing::debug!("Is library: {:#?}", session.library);
    tracing::debug!("Optlevel: {:#?}", session.optlevel);
    tracing::debug!("Debug Info: {:#?}", session.debug_info);

    let path_cache: Vec<_> = modules
        .iter()
        .map(|x| (x.0.display().to_string(), x.1.clone()))
        .collect();
    let modules: Vec<_> = modules.iter().map(|x| x.2.clone()).collect();

    if args.ast {
        std::fs::write(
            session.output_file.with_extension("ast"),
            format!("{:#?}", modules),
        )?;
    }

    let program_ir = match lower_modules(&modules) {
        Ok(ir) => ir,
        Err(error) => {
            let report = edlang_check::lowering_error_to_report(error, &session);
            report.eprint(sources(path_cache))?;
            std::process::exit(1);
        }
    };

    if args.ir {
        std::fs::write(
            session.output_file.with_extension("ir"),
            format!("{:#?}", program_ir),
        )?;
    }

    let object_path =
        edlang_codegen_llvm::compile(&session, &program_ir).expect("failed to compile");

    let elapsed = start_time.elapsed();
    tracing::debug!("Done in {:?}", elapsed);

    Ok(object_path)
}