Skip to content

Commit

Permalink
refactor(compiler):split the basic functions
Browse files Browse the repository at this point in the history
  • Loading branch information
limuy2022 committed Mar 24, 2024
1 parent e4c6f37 commit 7fb3b9d
Show file tree
Hide file tree
Showing 7 changed files with 215 additions and 178 deletions.
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "trc"
version = "0.1.0"
version = "0.0.1"
edition = "2021"
authors = ["limuy"]
description = "a easy-learn programming language"
Expand Down
15 changes: 15 additions & 0 deletions examples/fast_pow.trc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# calculate a^b
func fastpow(a: int, b: int) int {
if b == 0 {
return 1
}
if b == 1 {
return a
}
tmp := fastpow(a, b / 2);
tmp = tmp * tmp;
if b % 2 != 0 {
tmp = tmp * a
}
return tmp;
}
4 changes: 2 additions & 2 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
pub const MAIN_MODULE_NAME: &str = "main";
pub const FLOAT_OVER_FLOW_LIMIT: usize = 18;
pub const VERSION: &str = "0.1.0";
pub static VERSION_DESTRUCT: (u8, u8, u8) = (0, 1, 0);
pub const VERSION: &str = "0.0.1";
pub static VERSION_DESTRUCT: (u8, u8, u8) = (0, 0, 1);
pub static HISTORY_FILE: &str = "~/.trc_history";
177 changes: 5 additions & 172 deletions src/compiler/ast.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
mod ast_base;
mod lexprocess;

use crate::compiler::token::TokenType::RightBigBrace;
use crate::{
base::{
Expand All @@ -19,45 +22,6 @@ use super::{
};
use crate::base::stdlib::FunctionInterface;

/// 过程间分析用的结构
#[derive(Default)]
struct LexProcess {
stack_type: Vec<TyIdxTy>,
pub is_global: bool,
}

impl LexProcess {
pub fn new() -> Self {
Self {
..Default::default()
}
}

pub fn new_type(&mut self, ty: TyIdxTy) {
self.stack_type.push(ty);
}

pub fn clear(&mut self) {
self.stack_type.clear();
}

pub fn get_last_ty(&self) -> Option<TyIdxTy> {
self.stack_type.last().copied()
}

/// pop two val at the top of stack
pub fn cal_val(&mut self, ty: TyIdxTy) {
assert!(self.stack_type.len() >= 2);
self.stack_type.pop();
self.stack_type.pop();
self.new_type(ty)
}

pub fn pop_last_ty(&mut self) -> Option<TyIdxTy> {
self.stack_type.pop()
}
}

#[derive(Default)]
struct Cache {
pub(crate) intty_id: TyIdxTy,
Expand All @@ -79,7 +43,7 @@ pub struct AstBuilder<'a> {
pub token_lexer: TokenLex<'a>,
pub staticdata: StaticData,
self_scope: Rc<RefCell<SymScope>>,
process_info: LexProcess,
process_info: lexprocess::LexProcess,
cache: Cache,
// record if the fisrt func is defined
first_func: bool,
Expand Down Expand Up @@ -154,68 +118,6 @@ macro_rules! expr_gen {
}

impl<'a> AstBuilder<'a> {
pub fn clear_inst(&mut self) {
self.staticdata.inst.clear();
self.staticdata.function_split = None;
self.first_func = false
}

fn report_error<T>(&self, info: ErrorInfo) -> AstError<T> {
self.token_lexer.compiler_data.report_compiler_error(info)
}

#[inline]
pub fn try_err<T>(&self, istry: bool, info: ErrorInfo) -> AstError<T> {
if istry {
Err(LightFakeError::new().into())
} else {
self.report_error(info)
}
}

/// 获取对应类型的真实大小(内存对齐后)
pub fn get_ty_sz(&self, id: TyIdxTy) -> usize {
match self.convert_id_to_vm_ty(id) {
VmStackType::Int => size_of::<i64>(),
VmStackType::Float => size_of::<f64>(),
VmStackType::Str => size_of::<*mut String>(),
VmStackType::Char => size_of::<char>(),
VmStackType::Bool => size_of::<bool>(),
VmStackType::Object => get_trcobj_sz(),
}
}

pub fn convert_vm_ty_to_id(&self, ty: VmStackType) -> TyIdxTy {
match ty {
VmStackType::Int => self.cache.intty_id,
VmStackType::Float => self.cache.floatty_id,
VmStackType::Str => self.cache.strty_id,
VmStackType::Char => self.cache.charty_id,
VmStackType::Bool => self.cache.boolty_id,
VmStackType::Object => unreachable!(),
}
}

/// make sure code safe,by using match instead of if
pub fn convert_id_to_vm_ty(&self, ty: TyIdxTy) -> VmStackType {
if ty == self.cache.intty_id {
return VmStackType::Int;
}
if ty == self.cache.floatty_id {
return VmStackType::Float;
}
if ty == self.cache.strty_id {
return VmStackType::Str;
}
if ty == self.cache.charty_id {
return VmStackType::Char;
}
if ty == self.cache.boolty_id {
return VmStackType::Bool;
}
VmStackType::Object
}

pub fn new(mut token_lexer: TokenLex<'a>) -> Self {
let prelude = get_stdlib().sub_modules.get("prelude").unwrap();
for i in &prelude.functions {
Expand Down Expand Up @@ -245,7 +147,7 @@ impl<'a> AstBuilder<'a> {
token_lexer,
staticdata: StaticData::new(),
self_scope: root_scope,
process_info: LexProcess::new(),
process_info: lexprocess::LexProcess::new(),
cache,
first_func: false,
}
Expand Down Expand Up @@ -397,25 +299,6 @@ impl<'a> AstBuilder<'a> {
}
}

fn get_type_id_internel(
scope: Rc<RefCell<SymScope>>,
const_pool: &ValuePool,
ty_name: &str,
) -> Option<usize> {
scope
.as_ref()
.borrow()
.get_type(*const_pool.name_pool.get(ty_name).unwrap())
}

fn get_type_id(&self, ty_name: &str) -> Option<usize> {
Self::get_type_id_internel(
self.self_scope.clone(),
&self.token_lexer.const_pool,
ty_name,
)
}

fn move_val_into_obj_stack(&mut self) {
let obj_top = self.process_info.stack_type.last().copied().unwrap();
match self.convert_id_to_vm_ty(obj_top) {
Expand Down Expand Up @@ -630,24 +513,6 @@ impl<'a> AstBuilder<'a> {
}
}

fn get_ty(&mut self, istry: bool) -> AstError<TyIdxTy> {
let t = self.get_token_checked(TokenType::ID)?;
let ty = match self.self_scope.as_ref().borrow().get_type(t.data.unwrap()) {
None => self.try_err(
istry,
ErrorInfo::new(
t!(
SYMBOL_NOT_FOUND,
"0" = self.token_lexer.const_pool.id_name[t.data.unwrap()]
),
t!(TYPE_ERROR),
),
)?,
Some(v) => v,
};
Ok(ty)
}

fn def_func(&mut self) -> AstError<()> {
let funcname = self.get_token_checked(TokenType::ID)?.data.unwrap();
let name_id = match self.self_scope.as_ref().borrow_mut().insert_sym(funcname) {
Expand Down Expand Up @@ -710,21 +575,6 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

fn gen_error<T>(&self, e: ErrorInfo) -> AstError<T> {
self.try_err(false, e)
}

fn get_token_checked(&mut self, ty: TokenType) -> AstError<Token> {
let t = self.token_lexer.next_token()?;
if t.tp != ty {
self.gen_error(ErrorInfo::new(
t!(UNEXPECTED_TOKEN, "0" = t.tp),
t!(SYNTAX_ERROR),
))?;
}
Ok(t)
}

fn def_class(&mut self) -> AstError<()> {
Ok(())
}
Expand Down Expand Up @@ -910,13 +760,6 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

fn del_opcode(&mut self) -> Result<(), ()> {
match self.staticdata.inst.pop() {
Some(_) => Ok(()),
None => Err(()),
}
}

fn statement(&mut self) -> RunResult<()> {
let t = self.token_lexer.next_token()?;
match t.tp {
Expand Down Expand Up @@ -1050,16 +893,6 @@ impl<'a> AstBuilder<'a> {
self.generate_func_in_scope()?;
Ok(())
}

pub fn add_bycode(&mut self, opty: Opcode, opnum: usize) {
self.staticdata.inst.push(Inst::new(opty, opnum));
if !self.token_lexer.compiler_data.option.optimize {
// 不生成行号表了
self.staticdata
.line_table
.push(self.token_lexer.compiler_data.context.get_line())
}
}
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit 7fb3b9d

Please sign in to comment.