duskphantom_middle/
lib.rs

1// Copyright 2024 Duskphantom Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// SPDX-License-Identifier: Apache-2.0
16
17use duskphantom_frontend as frontend;
18use duskphantom_utils::mem::ObjPtr;
19use ir::ir_builder::IRBuilder;
20use transform::ultimate_pass;
21
22pub mod analysis;
23pub mod config;
24pub mod errors;
25pub mod ir;
26pub mod irgen;
27pub mod transform;
28
29use std::pin::Pin;
30
31pub struct Program {
32    pub module: ir::Module,
33    pub mem_pool: Pin<Box<IRBuilder>>,
34}
35
36use anyhow::{Context, Result};
37use duskphantom_utils::context;
38
39impl TryFrom<&frontend::Program> for Program {
40    type Error = anyhow::Error;
41    fn try_from(program: &frontend::Program) -> Result<Self> {
42        irgen::gen(program).with_context(|| context!())
43    }
44}
45impl TryFrom<frontend::Program> for Program {
46    type Error = anyhow::Error;
47    fn try_from(program: frontend::Program) -> Result<Self> {
48        irgen::gen(&program)
49    }
50}
51
52pub fn optimize(program: &mut Program, level: usize) {
53    if level == 0 {
54        return;
55    }
56    ultimate_pass::optimize_program(program, level).unwrap();
57}
58
59impl Default for Program {
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl Program {
66    pub fn new() -> Self {
67        let program_mem_pool = Box::pin(IRBuilder::new());
68        let mem_pool: ObjPtr<IRBuilder> = ObjPtr::new(&program_mem_pool);
69        Self {
70            mem_pool: program_mem_pool,
71            module: ir::Module::new(mem_pool),
72        }
73    }
74}
75
76impl Drop for Program {
77    fn drop(&mut self) {
78        self.mem_pool.clear();
79    }
80}