Skip to content

Commit 8859629

Browse files
committed
feat: add trait
1 parent 8f5e10f commit 8859629

File tree

17 files changed

+395
-261
lines changed

17 files changed

+395
-261
lines changed

src/ast/builder.rs renamed to src/ast/builder/llvmbuilder.rs

Lines changed: 193 additions & 210 deletions
Large diffs are not rendered by default.

src/ast/builder/mod.rs

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
/// 为以后codegen逻辑完全分离作准备,此包代码应该遵循以下原则:
2+
/// 1. 所有Builder的字段都应该private,不应该被外部直接访问
3+
/// 2. 所有涉及llvm类型的函数(包括参数或返回值)都应该是private的
4+
pub mod llvmbuilder;
5+
use std::{
6+
cell::{Cell, RefCell},
7+
path::Path,
8+
rc::Rc,
9+
};
10+
11+
use inkwell::{
12+
basic_block::BasicBlock,
13+
builder::Builder,
14+
context::Context,
15+
debug_info::*,
16+
module::{Linkage, Module},
17+
targets::TargetMachine,
18+
types::{ArrayType, BasicType, BasicTypeEnum, StructType},
19+
values::{
20+
AnyValue, AnyValueEnum, BasicMetadataValueEnum, BasicValue, BasicValueEnum, FunctionValue,
21+
PointerValue,
22+
},
23+
AddressSpace, FloatPredicate, IntPredicate,
24+
};
25+
use rustc_hash::FxHashMap;
26+
27+
use super::{
28+
ctx::{Ctx, MemberType, PLDiag},
29+
diag::ErrorCode,
30+
node::{types::TypedIdentifierNode, TypeNode, TypeNodeEnum},
31+
pltype::{ARRType, FNType, Field, PLType, PriType, RetTypeEnum, STType},
32+
range::{Pos, Range},
33+
};
34+
35+
36+
pub trait IRBuilder<'a, 'ctx> {
37+
fn get_global_var_handle(&self, name: &str) -> Option<ValueHandle>;
38+
fn new_subscope(&self, start: Pos);
39+
fn add_global(
40+
&self,
41+
name: &str,
42+
pltype: Rc<RefCell<PLType>>,
43+
ctx: &mut Ctx<'a>,
44+
line: u32,
45+
pltp: &PLType,
46+
) -> ValueHandle;
47+
fn alloc_vtp(&self, name: &str, v: ValueHandle) -> ValueHandle;
48+
fn alloc(&self, name: &str, pltype: &PLType, ctx: &mut Ctx<'a>) -> ValueHandle;
49+
fn build_conditional_branch(
50+
&self,
51+
cond: ValueHandle,
52+
then_bb: BlockHandle,
53+
else_bb: BlockHandle,
54+
);
55+
fn build_const_in_bounds_gep(&self, ptr: ValueHandle, index: &[u64], name: &str)
56+
-> ValueHandle;
57+
fn build_dbg_location(&self, pos: Pos);
58+
fn build_in_bounds_gep(
59+
&self,
60+
ptr: ValueHandle,
61+
index: &[ValueHandle],
62+
name: &str,
63+
) -> ValueHandle;
64+
fn build_return(&self, v: Option<ValueHandle>);
65+
fn build_store(&self, ptr: ValueHandle, value: ValueHandle);
66+
fn build_struct_gep(
67+
&self,
68+
structv: ValueHandle,
69+
index: u32,
70+
name: &str,
71+
) -> Result<ValueHandle, ()>;
72+
fn build_sub_program(
73+
&self,
74+
paralist: Vec<Box<TypedIdentifierNode>>,
75+
ret: Box<TypeNodeEnum>,
76+
fntype: &FNType,
77+
fnvalue: ValueHandle,
78+
child: &mut Ctx<'a>,
79+
) -> Result<(), PLDiag>;
80+
fn clear_insertion_position(&self);
81+
fn const_string(&self, s: &str) -> ValueHandle;
82+
fn create_parameter_variable(
83+
&self,
84+
fntype: &FNType,
85+
pos: Pos,
86+
i: usize,
87+
child: &mut Ctx<'a>,
88+
fnvalue: ValueHandle,
89+
alloca: ValueHandle,
90+
allocab: BlockHandle,
91+
);
92+
fn delete_block(&self, b: BlockHandle);
93+
fn finalize_debug(&self);
94+
fn float_value(&self, ty: &PriType, v: f64) -> ValueHandle;
95+
fn get_first_basic_block(&self, v: ValueHandle) -> BlockHandle;
96+
fn get_first_instruction(&self, bb: BlockHandle) -> Option<ValueHandle>;
97+
fn get_last_basic_block(&self, v: ValueHandle) -> BlockHandle;
98+
fn insert_var_declare(
99+
&self,
100+
name: &str,
101+
pos: Pos,
102+
pltype: &PLType,
103+
v: ValueHandle,
104+
ctx: &mut Ctx<'a>,
105+
);
106+
fn int_value(&self, ty: &PriType, v: u64, sign_ext: bool) -> ValueHandle;
107+
fn position_at(&self, v: ValueHandle);
108+
fn print_to_file(&self, file: &Path) -> Result<(), String>;
109+
fn rm_curr_debug_location(&self);
110+
fn try_set_fn_dbg(&self, pos: Pos, f: ValueHandle);
111+
fn write_bitcode_to_path(&self, path: &Path) -> bool;
112+
fn build_unconditional_branch(&self, bb: BlockHandle);
113+
fn position_at_end_block(&self, block: BlockHandle);
114+
fn add_body_to_struct_type(&self, name: &str, order_fields: &[Field], ctx: &mut Ctx<'a>);
115+
fn get_or_insert_fn_handle(&self, pltp: &FNType, ctx: &mut Ctx<'a>) -> ValueHandle;
116+
fn mv2heap(&self, val: ValueHandle, ctx: &mut Ctx<'a>) -> ValueHandle;
117+
fn gc_add_root(&self, stackptr: BasicValueEnum<'ctx>, ctx: &mut Ctx<'a>);
118+
fn gc_rm_root(&self, stackptr: ValueHandle, ctx: &mut Ctx<'a>);
119+
fn gc_rm_root_current(&self, stackptr: ValueHandle, ctx: &mut Ctx<'a>);
120+
fn gc_collect(&self, ctx: &mut Ctx<'a>);
121+
fn get_or_add_global(
122+
&self,
123+
name: &str,
124+
pltype: Rc<RefCell<PLType>>,
125+
ctx: &mut Ctx<'a>,
126+
) -> ValueHandle;
127+
fn build_load(&self, ptr: ValueHandle, name: &str) -> ValueHandle;
128+
fn try_load2var(
129+
&self,
130+
range: Range,
131+
v: ValueHandle,
132+
tp: Rc<RefCell<PLType>>,
133+
ctx: &mut Ctx<'a>,
134+
) -> Result<(ValueHandle, Rc<RefCell<PLType>>), PLDiag>;
135+
fn get_function(&self, name: &str) -> Option<ValueHandle>;
136+
fn build_call(&self, f: ValueHandle, args: &[ValueHandle]) -> Option<ValueHandle>;
137+
fn add_function(
138+
&self,
139+
name: &str,
140+
paramtps: &[PLType],
141+
ret: PLType,
142+
ctx: &mut Ctx<'a>,
143+
) -> ValueHandle;
144+
fn opaque_struct_type(&self, name: &str);
145+
fn build_int_z_extend(&self, v: ValueHandle, ty: &PriType, name: &str) -> ValueHandle;
146+
fn build_or(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
147+
fn build_and(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
148+
fn build_float_compare(
149+
&self,
150+
op: FloatPredicate,
151+
lhs: ValueHandle,
152+
rhs: ValueHandle,
153+
name: &str,
154+
) -> ValueHandle;
155+
fn build_int_compare(
156+
&self,
157+
op: IntPredicate,
158+
lhs: ValueHandle,
159+
rhs: ValueHandle,
160+
name: &str,
161+
) -> ValueHandle;
162+
fn build_int_add(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
163+
fn build_int_sub(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
164+
fn build_int_mul(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
165+
fn build_int_signed_div(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
166+
fn build_float_neg(&self, v: ValueHandle, name: &str) -> ValueHandle;
167+
fn build_float_add(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
168+
fn build_float_sub(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
169+
fn build_float_mul(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
170+
fn build_float_div(&self, lhs: ValueHandle, rhs: ValueHandle, name: &str) -> ValueHandle;
171+
fn append_basic_block(&self, func: ValueHandle, name: &str) -> BlockHandle;
172+
fn build_int_truncate(&self, v: ValueHandle, dest_ty: &PriType, name: &str) -> ValueHandle;
173+
fn build_int_neg(&self, v: ValueHandle, name: &str) -> ValueHandle;
174+
}
175+
176+
177+
pub type ValueHandle = usize;
178+
pub type BlockHandle = usize;
179+

src/ast/compiler.rs

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use super::{dot, node::program::ModWrapper};
22
use crate::{
33
ast::{
44
accumulators::{Diagnostics, ModBuffer},
5-
node::program::Program,
5+
node::program::Program, builder::llvmbuilder::get_target_machine,
66
},
77
lsp::mem_docs::{FileCompileInput, MemDocsInput},
88
nomparser::parse,
@@ -64,25 +64,6 @@ impl HashOptimizationLevel {
6464

6565
type MainFunc = unsafe extern "C" fn() -> i64;
6666

67-
pub fn get_target_machine(level: OptimizationLevel) -> TargetMachine {
68-
let triple = &TargetMachine::get_default_triple();
69-
let s1 = TargetMachine::get_host_cpu_name();
70-
let cpu = s1.to_str().unwrap();
71-
let s2 = TargetMachine::get_host_cpu_features();
72-
let features = s2.to_str().unwrap();
73-
Target::initialize_native(&InitializationConfig::default()).unwrap();
74-
let target = Target::from_triple(triple).unwrap();
75-
target
76-
.create_target_machine(
77-
triple,
78-
cpu,
79-
features,
80-
level,
81-
inkwell::targets::RelocMode::Static,
82-
inkwell::targets::CodeModel::Default,
83-
)
84-
.unwrap()
85-
}
8667

8768
/// # ActionType
8869
/// lsp action type

src/ast/ctx.rs

Lines changed: 5 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use super::builder::BlockHandle;
2-
use super::builder::LLVMBuilder;
2+
use crate::ast::builder::llvmbuilder::LLVMBuilder;use crate::ast::builder::IRBuilder;
33
use super::builder::ValueHandle;
4-
use super::compiler::get_target_machine;
4+
use super::builder::llvmbuilder::get_target_machine;
55
use super::diag::{ErrorCode, WarnCode};
66
use super::diag::{ERR_MSG, WARN_MSG};
77
use super::node::NodeEnum;
@@ -507,13 +507,6 @@ pub fn create_llvm_deps<'ctx>(
507507

508508
impl<'a, 'ctx> Ctx<'a> {
509509
pub fn new(
510-
// context: &'ctx Context,
511-
// module: &'a Module<'ctx>,
512-
// builder: &'a Builder<'ctx>,
513-
// dibuilder: &'a DebugInfoBuilder<'ctx>,
514-
// diunit: &'a DICompileUnit<'ctx>,
515-
// tm: &'a TargetMachine,
516-
// nodbg_builder: &'a Builder<'ctx>,
517510
src_file_path: &'a str,
518511
errs: &'a RefCell<Vec<PLDiag>>,
519512
edit_pos: Option<Pos>,
@@ -534,15 +527,6 @@ impl<'a, 'ctx> Ctx<'a> {
534527
father: None,
535528
init_func: None,
536529
function: None,
537-
// llbuilder: RefCell::new(LLVMBuilder::new(
538-
// context,
539-
// module,
540-
// builder,
541-
// dibuilder,
542-
// diunit,
543-
// tm,
544-
// nodbg_builder,
545-
// )),
546530
errs,
547531
edit_pos,
548532
table: FxHashMap::default(),
@@ -565,7 +549,6 @@ impl<'a, 'ctx> Ctx<'a> {
565549
generic_types: FxHashMap::default(),
566550
plmod: self.plmod.new_child(),
567551
father: Some(self),
568-
// llbuilder: RefCell::new(self.llbuilder.borrow().new_child()),
569552
errs: self.errs,
570553
edit_pos: self.edit_pos.clone(),
571554
table: FxHashMap::default(),
@@ -591,7 +574,6 @@ impl<'a, 'ctx> Ctx<'a> {
591574
generic_types: FxHashMap::default(),
592575
plmod: self.plmod.new_child(),
593576
father: Some(self),
594-
// llbuilder: RefCell::new(self.llbuilder.borrow().new_child()),
595577
errs: self.errs,
596578
edit_pos: self.edit_pos.clone(),
597579
table: FxHashMap::default(),
@@ -736,13 +718,13 @@ impl<'a, 'ctx> Ctx<'a> {
736718
for (_, sub) in &self.plmod.clone().submods {
737719
self.init_global_walk(&sub, &mut set, builder);
738720
}
739-
let a: &[ValueHandle] = &[];
721+
740722
builder.rm_curr_debug_location();
741723
builder.build_call(
742724
builder
743725
.get_function(&self.plmod.get_full_name("__init_global"))
744726
.unwrap(),
745-
a.iter(),
727+
&[],
746728
);
747729
}
748730
fn init_global_walk<'b>(
@@ -759,9 +741,8 @@ impl<'a, 'ctx> Ctx<'a> {
759741
self.init_global_walk(sub, set, builder);
760742
}
761743
let f = builder.add_function(&name, &[], PLType::VOID, self);
762-
let a: &[ValueHandle] = &[];
763744
builder.rm_curr_debug_location();
764-
builder.build_call(f, a.iter());
745+
builder.build_call(f, &[]);
765746
set.insert(name);
766747
}
767748

src/ast/node/function.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ impl Node for FuncCallNode {
148148
if let Some(f) = ctx.function {
149149
builder.try_set_fn_dbg(self.range.start, f);
150150
};
151-
let ret = builder.build_call(function, para_values.iter());
151+
let ret = builder.build_call(function, &para_values);
152152
ctx.save_if_comment_doc_hover(id_range, Some(fntype.doc.clone()));
153153
let res = match ret {
154154
Some(v) => Ok((

src/ast/node/global.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use super::*;
2+
use crate::ast::builder::llvmbuilder::LLVMBuilder;use crate::ast::builder::IRBuilder;
23
use crate::ast::diag::ErrorCode;
34

45
use internal_macro::{fmt, range};

src/ast/node/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::rc::Rc;
33

44
use crate::ast::ctx::Ctx;
55

6+
use crate::ast::builder::llvmbuilder::LLVMBuilder;use crate::ast::builder::IRBuilder;
67
use as_any::AsAny;
78
use enum_dispatch::enum_dispatch;
89

@@ -23,7 +24,7 @@ use self::statement::*;
2324
use self::string_literal::StringNode;
2425
use self::types::*;
2526

26-
use super::builder::{LLVMBuilder, ValueHandle};
27+
use super::builder::{ValueHandle};
2728
use super::ctx::PLDiag;
2829
use super::diag::ErrorCode;
2930
use super::fmt::FmtBuilder;

src/ast/node/operator.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use super::primary::VarNode;
22
use super::*;
3+
use crate::ast::builder::llvmbuilder::LLVMBuilder;use crate::ast::builder::IRBuilder;
34
use crate::ast::ctx::Ctx;
45
use crate::ast::diag::ErrorCode;
56
use crate::ast::pltype::PLType;
@@ -9,6 +10,7 @@ use crate::handle_calc;
910
use crate::plv;
1011
use inkwell::IntPredicate;
1112
use internal_macro::comments;
13+
1214
use internal_macro::fmt;
1315
use internal_macro::range;
1416
use lsp_types::SemanticTokenType;

src/ast/node/pkg.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use std::path::PathBuf;
22

33
use crate::{
44
ast::{
5-
builder::LLVMBuilder,
65
ctx::{get_ns_path_completions, Ctx},
76
diag::ErrorCode,
87
node::{deal_line, tab},
@@ -12,6 +11,7 @@ use crate::{
1211
};
1312
use internal_macro::{fmt, range};
1413
use lsp_types::SemanticTokenType;
14+
use crate::ast::builder::llvmbuilder::LLVMBuilder;use crate::ast::builder::IRBuilder;
1515

1616
use super::{primary::VarNode, Node, NodeResult, PLValue, TerminatorEnum};
1717
#[range]

src/ast/node/pointer.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use super::*;
2+
use crate::ast::builder::llvmbuilder::LLVMBuilder;use crate::ast::builder::IRBuilder;
23
use crate::{
34
ast::{ctx::Ctx, diag::ErrorCode},
45
plv,

0 commit comments

Comments
 (0)