From 565ad6b88c23c78216e7d170f04a553c7da41eb3 Mon Sep 17 00:00:00 2001 From: subkey <2822448396@qq.com> Date: Sun, 25 Feb 2024 11:51:56 +0800 Subject: [PATCH] =?UTF-8?q?if=20=E5=92=8Cwhile=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- samples/helloworld.ks | 8 ++- spec/classes.md | 2 +- spec/declare.md | 4 +- spec/loop.md | 13 ++-- src/main.rs | 3 +- src/runtime/call.rs | 6 +- src/runtime/evil.rs | 127 +++++++++++++++++++++++++++++++++++----- src/runtime/externer.rs | 1 - src/runtime/mod.rs | 78 +++++++++++++----------- src/runtime/outlive.rs | 13 +--- src/scan/literal.rs | 12 ++-- src/scan/mod.rs | 8 +-- src/scan/stmt.rs | 66 ++++++++++++++------- 13 files changed, 232 insertions(+), 109 deletions(-) diff --git a/samples/helloworld.ks b/samples/helloworld.ks index 7edcda6..9c76030 100644 --- a/samples/helloworld.ks +++ b/samples/helloworld.ks @@ -1,3 +1,9 @@ -mod D:\code\rs\key-native\target\debug\key_native.dll> m +// mod D:\code\rs\key-native\target\debug\key_native.dll> m +let a=0 +for(a<5) { + a+=1; + log(a) + if a>3 break +} \ No newline at end of file diff --git a/spec/classes.md b/spec/classes.md index 182bb9d..23ed3c9 100644 --- a/spec/classes.md +++ b/spec/classes.md @@ -1,7 +1,7 @@ ## 定义结构 逗号可以省略 -首字母必须大写 +首字母建议大写 ``` class MyClass { a diff --git a/spec/declare.md b/spec/declare.md index 97d7508..2f909b9 100644 --- a/spec/declare.md +++ b/spec/declare.md @@ -24,10 +24,10 @@ let buf = 'Genshin{0F20}'; // Buffer(u8 {}内允许空格换行) ## 注释 ``` // 单行注释 -/` +/' 多行注释 多行注释 -`/ +'/ ``` 多行注释的结尾``/`省略的话就可以自动注释到文件结尾。 diff --git a/spec/loop.md b/spec/loop.md index b21afb5..0a9debb 100644 --- a/spec/loop.md +++ b/spec/loop.md @@ -1,10 +1,9 @@ -loop(20) { - -} -loop { - +for 200 {} // 循环200次(本质上是把200变成一个200次的迭代器) +for a: 200 {} // 循环200次并以a作为迭代器过程的值 +for!{} // 无限循环 +for(a<200) { // 就是while + a+=1 } -loop (let? i<50) { -} \ No newline at end of file +if和for后如果是单语句不是块就会在当前作用域直接执行,包括let和class \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 8168401..d0ecdd8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,6 +24,7 @@ fn main()-> ExitCode { // } // })); + // 把return_to也做一个run的版本 // 迭代器 loop // 基本类型的方法,也就是所有litr的prop @@ -60,7 +61,7 @@ fn main()-> ExitCode { intern::init(); let scanned = scan::scan(fs::read("D:\\code\\rs\\key-lang\\samples\\helloworld.ks").unwrap()); - // println!("{scanned:?}"); + println!("{scanned:?}"); let exit = runtime::run(&scanned); if let scan::literal::Litr::Int(code) = exit.returned { return ExitCode::from(code as u8); diff --git a/src/runtime/call.rs b/src/runtime/call.rs index a7901c8..1d2394b 100644 --- a/src/runtime/call.rs +++ b/src/runtime/call.rs @@ -42,17 +42,17 @@ impl Scope { let kself = if let Some(s) = f.bound {s}else {self.kself}; let mut ret = Litr::Uninit; - let mut return_to = Some(&mut ret as *mut Litr); let mut scope = Scope::new(ScopeInner { parent:Some(f.scope), - return_to:&mut return_to, + return_to:&mut ret, class_defs:Vec::new(), class_uses:Vec::new(), kself, vars, imports: self.imports, exports: self.exports, - outlives: Outlives::new() + outlives: Outlives::new(), + ended: false }); scope.run(&f.stmts); ret diff --git a/src/runtime/evil.rs b/src/runtime/evil.rs index 74039fa..57f3d51 100644 --- a/src/runtime/evil.rs +++ b/src/runtime/evil.rs @@ -19,20 +19,7 @@ impl Scope { self.vars.push((a.id, v)); } // 块语句 - Stmt::Block(s)=> { - let mut scope = Scope::new(ScopeInner { - parent:Some(*self), - return_to: self.return_to, - class_defs:Vec::new(), - class_uses:Vec::new(), - kself: self.kself, - vars: Vec::with_capacity(16), - imports: self.imports, - exports: self.exports, - outlives: Outlives::new() - }); - scope.run(s); - } + Stmt::Block(s)=> self.subscope().run(s), // 类型声明 Stmt::Class(raw)=> { @@ -109,8 +96,116 @@ impl Scope { module.classes.push((raw.name,ptr)) } - Stmt::Return(_)=> err!("return语句不应被直接evil"), - _=> {} + // 返回一个值 + Stmt::Return(expr)=> { + // 遇到return语句就停止当前遍历 + // 并将返回值指针相同(在同一函数内的作用域)设为已结束 + unsafe{*self.return_to = self.calc(expr)}; + self.ended = true; + let mut scope = *self; + while let Some(mut s) = scope.parent { + if s.return_to != self.return_to {break;} + s.ended = true; + scope = s; + } + }, + + // if else + Stmt::If { condition, exec, els }=> { + if cond(self.calc(condition)) { + self.evil(exec) + }else if let Some(els) = els { + self.evil(els) + } + } + + // for ()语句 + Stmt::ForWhile { condition, exec }=> { + // 用重置作用域代替重新创建作用域 + if let Stmt::Block(exec) = &**exec { + let mut scope = self.subscope(); + let mut breaked = false; + while cond(self.calc(condition)) { + if scope.ended || breaked { + outlive::scope_end(scope); + return; + } + scope.vars.clear(); + scope.class_uses.clear(); + loop_run(scope, &mut breaked, exec); + } + scope.ended = true; + outlive::scope_end(scope); + // 单语句将由当前作用域代为执行,不再创建新作用域 + }else { + match &**exec { + Stmt::Break=> err!("不允许`for() break`的写法"), + Stmt::Continue=> err!("不允许`for() continue`的写法`"), + _=> while cond(self.calc(condition)) { + if self.ended { + return; + } + self.evil(exec); + } + } + } + } + Stmt::ForIter=>(), + Stmt::ForLoop=>(), + + Stmt::Match=>(), + + // - + Stmt::Break=> err!("break不在循环体内"), + Stmt::Continue=> err!("continue不在循环体内"), + Stmt::Empty=> (), + } + } +} + +/// 判断if后的条件 +fn cond(v:Litr)-> bool { + match v { + Litr::Bool(b)=> b, + Litr::Uninit=> false, + _=> err!("条件必须为Bool或uninit") + } +} + +/// 以循环模式运行一段语句 +fn loop_run(mut scope:Scope,breaked:&mut bool,exec:&Statements) { + macro_rules! loop_run_stmt {($stmt:expr)=>{{ + match $stmt { + Stmt::Block(exec)=> { + let mut s = scope.subscope(); + loop_run(s, breaked, exec); + s.ended = true; + outlive::scope_end(s); + }, + Stmt::Break=> *breaked = true, + _=> scope.evil($stmt) + }; + }}} + for (l, sm) in &exec.0 { + if scope.ended || *breaked { + // outlive::scope_end(scope); + return; + } + match sm { + Stmt::Break=> *breaked = true, + // 把直属该for下的块拦截,检测break和continue + Stmt::Block(v)=> loop_run(scope, breaked, exec), + Stmt::If { condition, exec, els }=> { + if cond(scope.calc(condition)) { + loop_run_stmt!(&**exec) + }else if let Some(els) = els { + loop_run_stmt!(&**els) + } + }, + _=> { + unsafe{LINE = *l;} + scope.evil(sm); + } } } } \ No newline at end of file diff --git a/src/runtime/externer.rs b/src/runtime/externer.rs index 2e4560f..36bc0d6 100644 --- a/src/runtime/externer.rs +++ b/src/runtime/externer.rs @@ -9,7 +9,6 @@ use crate::c::{dlopen,dlsym}; use crate::scan::literal::{ Litr, LocalFunc }; -use crate::runtime::ScopeInner; static mut EXEC:Option = None; diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs index 5c24036..e7d3959 100644 --- a/src/runtime/mod.rs +++ b/src/runtime/mod.rs @@ -51,8 +51,8 @@ pub enum Class { pub struct ScopeInner { /// 父作用域 pub parent: Option, - /// 返回值指针,None代表已返回 - pub return_to: *mut Option<*mut Litr>, + /// 返回值指针 + pub return_to: *mut Litr, /// (变量名,值) pub vars: Vec<(Interned, Litr)>, /// 类型声明(和作用域生命周期一致) @@ -66,7 +66,10 @@ pub struct ScopeInner { /// ks本身作为模块导出的指针 pub exports: *mut LocalMod, /// 该作用域生命周期会被outlive的函数延长 - pub outlives: outlive::Outlives + pub outlives: outlive::Outlives, + /// 遇到return时会提前变为true + /// 用于标识return. break有自己的判断方法 + pub ended: bool } @@ -79,12 +82,25 @@ pub struct ScopeInner { pub struct Scope { pub ptr:*mut ScopeInner } +impl std::ops::Deref for Scope { + type Target = ScopeInner; + fn deref(&self) -> &Self::Target { + unsafe {&*self.ptr} + } +} +impl std::ops::DerefMut for Scope { + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe {&mut *self.ptr} + } +} + impl Scope { pub fn new(s:ScopeInner)-> Self { Scope { ptr: Box::into_raw(Box::new(s)) } } + /// 确认此作用域是否为一个作用域的子作用域 pub fn subscope_of(&self,upper:Scope)-> bool { let mut scope = *self; @@ -100,47 +116,39 @@ impl Scope { } false } -} -impl std::ops::Deref for Scope { - type Target = ScopeInner; - fn deref(&self) -> &Self::Target { - unsafe {&*self.ptr} - } -} -impl std::ops::DerefMut for Scope { - fn deref_mut(&mut self) -> &mut Self::Target { - unsafe {&mut *self.ptr} + + /// 生成一个子作用域 + pub fn subscope(&self)-> Scope { + Scope::new(ScopeInner { + parent:Some(*self), + return_to: self.return_to, + class_defs:Vec::new(), + class_uses:Vec::new(), + kself: self.kself, + vars: Vec::with_capacity(16), + imports: self.imports, + exports: self.exports, + outlives: Outlives::new(), + ended: false + }) } -} -impl Scope { /// 在此作用域运行ast代码 /// /// 此行为会根据引用计数回收作用域,在run之后再次使用Scope是未定义行为 pub fn run(mut self, codes:&Statements) { for (l, sm) in &codes.0 { + // 运行一行语句 unsafe{LINE = *l;} + self.evil(sm); - // 如果子作用域返回过了,这里就会是None状态 - let return_to = unsafe{&*self.return_to}; - if let None = return_to { - return; - } - - // 遇到return语句就停止当前遍历 - if let Stmt::Return(expr) = sm { - unsafe { - if let Some(p) = return_to { - **p = self.calc(expr); - } - *self.return_to = None; - } + // 停止已结束的作用域 + if self.ended { outlive::scope_end(self); return; } - - self.evil(sm); } + self.ended = true; outlive::scope_end(self); } @@ -249,18 +257,17 @@ pub struct RunResult { /// 创建顶级作用域并运行一段程序 pub fn run(s:&Statements)-> RunResult { let mut top_ret = Litr::Uint(0); - let mut return_to = &mut Some(&mut top_ret as *mut Litr); let mut imports = Vec::new(); let mut exports = LocalMod { name: intern(b"mod"), funcs: Vec::new(), classes: Vec::new() }; let mut kself = Litr::Uninit; - top_scope(return_to, &mut imports, &mut exports,&mut kself).run(s); + top_scope(&mut top_ret, &mut imports, &mut exports,&mut kself).run(s); RunResult { returned: top_ret, exports, kself } } /// 创建顶级作用域 /// /// 自定义此函数可添加初始函数和变量 -pub fn top_scope(return_to:*mut Option<*mut Litr>, imports:*mut Vec, exports:*mut LocalMod, kself:*mut Litr)-> Scope { +pub fn top_scope(return_to:*mut Litr, imports:*mut Vec, exports:*mut LocalMod, kself:*mut Litr)-> Scope { let mut vars = Vec::<(Interned, Litr)>::with_capacity(16); vars.push((intern(b"log"), Litr::Func(Function::Native(crate::primitive::std::log))) @@ -276,6 +283,7 @@ pub fn top_scope(return_to:*mut Option<*mut Litr>, imports:*mut Vec, exp imports, exports, vars, - outlives: Outlives::new() + outlives: Outlives::new(), + ended: false }) } diff --git a/src/runtime/outlive.rs b/src/runtime/outlive.rs index 0f1205d..d70699f 100644 --- a/src/runtime/outlive.rs +++ b/src/runtime/outlive.rs @@ -3,7 +3,6 @@ //! 具体思路见Outlives结构 use super::{LocalFuncRaw, LocalFunc}; -use super::ScopeInner; use std::sync::atomic::Ordering; @@ -20,18 +19,13 @@ pub struct Outlives { /// 该作用域得到的延长了生命周期的函数列表 /// /// 在该作用域结束时会为列表中所有函数减少一层`count` - to_drop: Vec, - /// 在回收函数定义处的作用域时有可能会提前回收未结束的作用域 - /// - /// 此标志用来标识作用域是否执行完成 - ended: bool + to_drop: Vec } impl Outlives { pub fn new()-> Self { Outlives { count:AtomicUsize::new(0), - to_drop:Vec::new(), - ended: false + to_drop:Vec::new() } } } @@ -73,7 +67,6 @@ pub fn outlive_static(mut scope:Scope) { /// 若引用计数为0就回收作用域 pub fn scope_end(mut scope:Scope) { // 回收作用域本身 - scope.outlives.ended = true; if scope.outlives.count.load(Ordering::Relaxed) == 0 { unsafe { std::ptr::drop_in_place(scope.ptr) } } @@ -83,7 +76,7 @@ pub fn scope_end(mut scope:Scope) { fn sub_count(mut scope: Scope) { loop { let prev = scope.outlives.count.fetch_sub(1, Ordering::Relaxed); - if prev == 1 && scope.outlives.ended { + if prev == 1 && scope.ended { unsafe{ std::ptr::drop_in_place(scope.ptr) } } if let Some(prt) = scope.parent { diff --git a/src/scan/literal.rs b/src/scan/literal.rs index 00e1754..3514ab8 100644 --- a/src/scan/literal.rs +++ b/src/scan/literal.rs @@ -453,7 +453,7 @@ impl Scanner<'_> { self.next(); Expr::List(ls) } - + // 解析对象 b'{'=> Expr::Obj(self.obj()), @@ -469,12 +469,10 @@ impl Scanner<'_> { _=> { self.spaces(); if self.cur() == b'{' { - if id[0].is_ascii_uppercase() { - let decl = self.obj(); - return Expr::NewInst{ - cls: intern(id), - val: decl - }; + let decl = self.obj(); + return Expr::NewInst{ + cls: intern(id), + val: decl } } Expr::Variant(intern(id)) diff --git a/src/scan/mod.rs b/src/scan/mod.rs index 0635bc1..8fe5457 100644 --- a/src/scan/mod.rs +++ b/src/scan/mod.rs @@ -90,7 +90,7 @@ impl Scanner<'_> { /// 跳过一段空格,换行符和注释 fn spaces(&self) { let len = self.src.len(); - while self.i() < len { + loop { let c = self.cur(); if c == b'\n' { unsafe{*self.line += 1;} @@ -117,14 +117,14 @@ impl Scanner<'_> { self.next(); } // 多行 - if nc == b'`' { + if nc == b'\'' { self.set_i(next + 1); loop { self.next(); if self.cur() == b'\n' { unsafe{*self.line += 1;} } - if self.cur() == b'`' { + if self.cur() == b'\'' { let next = self.i() + 1; if next >= len { self.set_i(len); @@ -132,12 +132,12 @@ impl Scanner<'_> { } if self.src[next] == b'/' { self.set_i(next + 1); - break; } } } } } + continue; } _=> { break; diff --git a/src/scan/stmt.rs b/src/scan/stmt.rs index 14532ae..f13b821 100644 --- a/src/scan/stmt.rs +++ b/src/scan/stmt.rs @@ -31,18 +31,26 @@ pub enum Stmt { ExportFn (Interned, LocalFuncRaw), ExportCls (ClassDefRaw), - // Key - // Key (HashMap), // 类型声明语句 - // Impl (HashMap), // 方法定义语句 Match, // 模式匹配 // 块系列 Block (Statements), // 一个普通块 - If (Statements), // 条件语句 - Loop (Statements), // 循环 + If { + condition: Expr, + exec: Box, + els: Option> + }, + ForLoop, + ForWhile { + condition: Expr, + exec: Box + }, + ForIter, + // If (Statements), // 条件语句 + // Loop (Statements), // 循环 // 流程控制 - Break (Expr), // 中断循环并提供返回值 + Break, Continue, // 立刻进入下一次循环 Return (Expr), // 函数返回 @@ -156,33 +164,27 @@ impl Scanner<'_> { _=>{} } - let ident = self.ident(); - if let Some(id) = ident { - match id { + let ident = self.literal(); + if let Expr::Variant(id) = ident { + match &*id.vec() { // 如果是关键词,就会让对应函数处理关键词之后的信息 b"let"=> Stmt::Let(self.letting()), b"extern"=> {self.externing();Stmt::Empty}, b"return"=> self.returning(), b"class"=> self.classing(), b"mod"=> self.moding(), + b"for"=> self.foring(), + b"if"=> self.ifing(), + b"break"=> Stmt::Break, + b"continue"=> Stmt::Continue, b"async"|b"await"=> self.err("异步关键词暂未实现"), _=> { - let left = match &*id { - b"true"=> Expr::Literal(Litr::Bool(true)), - b"false"=> Expr::Literal(Litr::Bool(false)), - b"self"=> Expr::Kself, - b"uninit"=> Expr::Literal(Litr::Uninit), - _=> Expr::Variant(intern(id)) - }; - let expr = self.expr_with_left(left); + let expr = self.expr_with_left(ident); Stmt::Expression(expr) } } }else { - let expr = self.expr(); - if let Expr::Empty = expr { - self.err(&format!("请输入一行正确的语句,'{}'并不合法", String::from_utf8_lossy(&[self.cur()]))) - } + let expr = self.expr_with_left(ident); Stmt::Expression(expr) } } @@ -491,5 +493,27 @@ impl Scanner<'_> { _ => self.err("未知模块类型") } } + + fn ifing(&self)-> Stmt { + let condition = self.expr(); + let exec = Box::new(self.stmt()); + self.spaces(); + if self.cur() == b'e' { + + } + Stmt::If { condition, exec, els: None } + } + + /// for语句 + fn foring(&self)-> Stmt { + self.spaces(); + if self.cur() == b'(' { + let condition = self.expr_group(); + let exec = Box::new(self.stmt()); + Stmt::ForWhile { condition, exec } + }else { + self.err("for语法错误") + } + } }