Compare commits
No commits in common. "34a129d1018f884fce9ed0f736fff81f8b600f69" and "a6282c00eb260a56a17890463492536756183a58" have entirely different histories.
34a129d101
...
a6282c00eb
7 changed files with 577 additions and 846 deletions
79
src/expr.rs
79
src/expr.rs
|
@ -1,104 +1,92 @@
|
|||
use std::{
|
||||
boxed::Box,
|
||||
sync::{Arc, RwLock},
|
||||
|
||||
use {
|
||||
std::{
|
||||
boxed::Box,
|
||||
sync::{Arc, RwLock}
|
||||
}
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Statement {
|
||||
Assignment {
|
||||
var_id: String,
|
||||
val_expr: LTExpr,
|
||||
val_expr: LTExpr
|
||||
},
|
||||
LetAssign {
|
||||
typ: Option<TypeTag>,
|
||||
var_id: String,
|
||||
val_expr: LTExpr,
|
||||
},
|
||||
WhileLoop {
|
||||
condition: LTExpr,
|
||||
body: Vec<Statement>,
|
||||
body: Vec<Statement>
|
||||
},
|
||||
Return(LTExpr),
|
||||
Expr(LTExpr),
|
||||
Expr(LTExpr)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum TypeError {
|
||||
ParseError(laddertypes::parser::ParseError),
|
||||
Mismatch {
|
||||
expected: laddertypes::TypeTerm,
|
||||
received: laddertypes::TypeTerm,
|
||||
},
|
||||
}
|
||||
|
||||
pub type TypeTag = Result<laddertypes::TypeTerm, TypeError>;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum LTExpr {
|
||||
Literal {
|
||||
typ: Option<TypeTag>,
|
||||
val: tisc::VM_Word,
|
||||
typ: Option< laddertypes::TypeTerm >,
|
||||
val: tisc::VM_Word
|
||||
},
|
||||
Symbol {
|
||||
typ: Option<TypeTag>,
|
||||
typ: Option< laddertypes::TypeTerm >,
|
||||
symbol: String,
|
||||
},
|
||||
Application {
|
||||
typ: Option<TypeTag>,
|
||||
head: Box<LTExpr>,
|
||||
body: Vec<LTExpr>,
|
||||
body: Vec<LTExpr>
|
||||
},
|
||||
Abstraction {
|
||||
args: Vec<(String, Option<TypeTag>)>,
|
||||
body: Box<LTExpr>,
|
||||
arg_id: String,
|
||||
arg_type: Option< laddertypes::TypeTerm >,
|
||||
val_expr: Box<LTExpr>
|
||||
},
|
||||
Branch {
|
||||
condition: Box<LTExpr>,
|
||||
if_expr: Box<LTExpr>,
|
||||
else_expr: Box<LTExpr>,
|
||||
else_expr: Box<LTExpr>
|
||||
},
|
||||
Block {
|
||||
statements: Vec<Statement>,
|
||||
},
|
||||
statements: Vec<Statement>
|
||||
}
|
||||
}
|
||||
|
||||
impl LTExpr {
|
||||
pub fn symbol(str: &str) -> Self {
|
||||
LTExpr::Symbol {
|
||||
typ: None, //typectx.write().unwrap().parse("<Ref memory::Word>~Symbol~<Seq Char>").expect("parse typeterm"),
|
||||
symbol: String::from(str),
|
||||
typ: None,//typectx.write().unwrap().parse("<Ref memory::Word>~Symbol~<Seq Char>").expect("parse typeterm"),
|
||||
symbol: String::from(str)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lit_uint(val: u64) -> Self {
|
||||
LTExpr::Literal {
|
||||
typ: None, //typectx.write().unwrap().parse("ℤ_2^64~machine::UInt64~machine::Word").expect("parse typeterm"),
|
||||
val: val as tisc::VM_Word,
|
||||
typ: None,//typectx.write().unwrap().parse("ℤ_2^64~machine::UInt64~machine::Word").expect("parse typeterm"),
|
||||
val: val as tisc::VM_Word
|
||||
}
|
||||
}
|
||||
|
||||
pub fn abstraction(args: Vec<(&str, &str)>, body: LTExpr) -> LTExpr {
|
||||
pub fn abstraction(arg_id: &str, arg_typ: &str, val_expr: LTExpr) -> LTExpr {
|
||||
LTExpr::Abstraction {
|
||||
args: args
|
||||
.into_iter()
|
||||
.map(
|
||||
|(arg_name, arg_type)| (arg_name.into(), None), //typectx.write().unwrap().parse(t).expect("parse typeterm")
|
||||
)
|
||||
.collect(),
|
||||
body: Box::new(body),
|
||||
arg_id: String::from(arg_id),
|
||||
arg_type: None,//typectx.write().unwrap().parse(arg_typ).expect("parse typeterm"),
|
||||
val_expr: Box::new(val_expr)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn application(head: LTExpr, body: Vec<LTExpr>) -> Self {
|
||||
LTExpr::Application {
|
||||
typ: None,
|
||||
head: Box::new(head),
|
||||
body: body,
|
||||
head: Box::new( head ),
|
||||
body: body
|
||||
}
|
||||
}
|
||||
|
||||
pub fn block(body: Vec<Statement>) -> Self {
|
||||
LTExpr::Block { statements: body }
|
||||
LTExpr::Block {
|
||||
statements: body
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -106,7 +94,7 @@ impl Statement {
|
|||
pub fn while_loop(cond: LTExpr, body: Vec<Statement>) -> Self {
|
||||
Statement::WhileLoop {
|
||||
condition: cond,
|
||||
body,
|
||||
body
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -153,3 +141,4 @@ impl LTExpr {
|
|||
}
|
||||
}
|
||||
*/
|
||||
|
||||
|
|
265
src/lexer.rs
265
src/lexer.rs
|
@ -1,15 +1,16 @@
|
|||
|
||||
#[derive(PartialEq, Eq, Clone, Debug)]
|
||||
pub enum LTIRToken {
|
||||
Symbol(String),
|
||||
Char(char),
|
||||
Num(i64),
|
||||
Symbol( String ),
|
||||
Char( char ),
|
||||
Num( i64 ),
|
||||
|
||||
// SingleQuote(String),
|
||||
// DoubleQuote(String),
|
||||
// TripleQuote(String),
|
||||
|
||||
Lambda,
|
||||
LambdaBody,
|
||||
AssignType(String),
|
||||
AssignType,
|
||||
AssignValue,
|
||||
|
||||
ExprOpen,
|
||||
|
@ -23,41 +24,37 @@ pub enum LTIRToken {
|
|||
#[derive(PartialEq, Eq, Clone, Debug)]
|
||||
pub enum LexError {
|
||||
InvalidDigit,
|
||||
InvalidChar,
|
||||
InvalidChar
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Clone, Debug)]
|
||||
pub enum LexerState {
|
||||
Any,
|
||||
TypeTerm(String),
|
||||
Sym(String),
|
||||
Num(i64),
|
||||
Char(Option<char>),
|
||||
Sym( String ),
|
||||
Num( i64 ),
|
||||
Char( Option<char> )
|
||||
}
|
||||
|
||||
impl LexerState {
|
||||
fn into_token(self) -> Option<LTIRToken> {
|
||||
fn into_token(self) -> Option< LTIRToken > {
|
||||
match self {
|
||||
LexerState::Any => None,
|
||||
LexerState::TypeTerm(s) => Some(LTIRToken::AssignType(s)),
|
||||
LexerState::Sym(s) => Some(LTIRToken::Symbol(s)),
|
||||
LexerState::Num(n) => Some(LTIRToken::Num(n)),
|
||||
LexerState::Char(c) => Some(LTIRToken::Char(c?)),
|
||||
LexerState::Char(c) => Some(LTIRToken::Char(c?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct LTIRLexer<It>
|
||||
where
|
||||
It: std::iter::Iterator<Item = char>,
|
||||
where It: std::iter::Iterator<Item = char>
|
||||
{
|
||||
chars: std::iter::Peekable<It>,
|
||||
position: usize
|
||||
}
|
||||
|
||||
impl<It> LTIRLexer<It>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
pub fn into_inner(self) -> std::iter::Peekable<It> {
|
||||
self.chars
|
||||
|
@ -65,196 +62,98 @@ where
|
|||
}
|
||||
|
||||
impl<It> From<It> for LTIRLexer<It>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
fn from(chars: It) -> Self {
|
||||
LTIRLexer {
|
||||
chars: chars.peekable(),
|
||||
position: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InputRegionTag {
|
||||
begin: usize,
|
||||
end: usize
|
||||
}
|
||||
|
||||
impl InputRegionTag {
|
||||
pub fn max( a: InputRegionTag, b: InputRegionTag ) -> InputRegionTag {
|
||||
InputRegionTag {
|
||||
begin: usize::min( a.begin, b.begin ),
|
||||
end: usize::max( a.end, b.end )
|
||||
chars: chars.peekable()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<It> Iterator for LTIRLexer<It>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
type Item = (InputRegionTag, Result<LTIRToken, LexError>);
|
||||
type Item = Result<LTIRToken, LexError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let mut state = LexerState::Any;
|
||||
let mut region = InputRegionTag{
|
||||
begin: self.position,
|
||||
end: self.position
|
||||
};
|
||||
|
||||
while let Some(c) = self.chars.peek() {
|
||||
match &mut state {
|
||||
|
||||
// determine token type
|
||||
LexerState::Any => match c {
|
||||
'λ' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
return Some((region, Ok(LTIRToken::Lambda)));
|
||||
}
|
||||
'.' | '↦' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
return Some((region, Ok(LTIRToken::LambdaBody)));
|
||||
}
|
||||
'(' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
return Some((region, Ok(LTIRToken::ExprOpen)));
|
||||
}
|
||||
')' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
return Some((region, Ok(LTIRToken::ExprClose)));
|
||||
}
|
||||
'{' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
return Some((region, Ok(LTIRToken::BlockOpen)));
|
||||
}
|
||||
'}' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
return Some((region, Ok(LTIRToken::BlockClose)));
|
||||
}
|
||||
':' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
state = LexerState::TypeTerm(String::new());
|
||||
}
|
||||
'=' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
return Some((region, Ok(LTIRToken::AssignValue)));
|
||||
}
|
||||
';' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
return Some((region, Ok(LTIRToken::StatementSep)));
|
||||
}
|
||||
'\'' => {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
state = LexerState::Char(None);
|
||||
}
|
||||
c => {
|
||||
if c.is_whitespace() {
|
||||
self.chars.next();
|
||||
self.position += 1;
|
||||
region.begin += 1;
|
||||
region.end += 1;
|
||||
} else if c.is_digit(10) {
|
||||
state = LexerState::Num(0);
|
||||
} else {
|
||||
state = LexerState::Sym(String::new());
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
LexerState::Char(val) => {
|
||||
self.position += 2;
|
||||
region.end += 2;
|
||||
*val = Some(match self.chars.next() {
|
||||
Some('\\') => {
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
match self.chars.next() {
|
||||
Some('0') => '\0',
|
||||
Some('n') => '\n',
|
||||
Some('t') => '\t',
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return Some((region, Err(LexError::InvalidChar)));
|
||||
}
|
||||
LexerState::Any => {
|
||||
match c {
|
||||
'λ' => { self.chars.next(); return Some(Ok(LTIRToken::Lambda)); },
|
||||
'(' => { self.chars.next(); return Some(Ok(LTIRToken::ExprOpen)); },
|
||||
')' => { self.chars.next(); return Some(Ok(LTIRToken::ExprClose)); },
|
||||
'{' => { self.chars.next(); return Some(Ok(LTIRToken::BlockOpen)); },
|
||||
'}' => { self.chars.next(); return Some(Ok(LTIRToken::BlockClose)); },
|
||||
':' => { self.chars.next(); return Some(Ok(LTIRToken::AssignType)); },
|
||||
'=' => { self.chars.next(); return Some(Ok(LTIRToken::AssignValue)); },
|
||||
';' => { self.chars.next(); return Some(Ok(LTIRToken::StatementSep)); },
|
||||
'\'' => { self.chars.next(); state = LexerState::Char(None); },
|
||||
c => {
|
||||
if c.is_whitespace() {
|
||||
self.chars.next();
|
||||
} else if c.is_digit(10) {
|
||||
state = LexerState::Num( 0 );
|
||||
} else {
|
||||
state = LexerState::Sym( String::new() );
|
||||
}
|
||||
},
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return Some((region, Err(LexError::InvalidChar)));
|
||||
}
|
||||
});
|
||||
|
||||
match self.chars.next() {
|
||||
Some('\'') => {
|
||||
if let Some(token) = state.clone().into_token() {
|
||||
return Some((region, Ok(token)));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Some((region, Err(LexError::InvalidChar)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LexerState::TypeTerm(s) => {
|
||||
if *c == '=' || *c == '.' {
|
||||
if let Some(token) = state.clone().into_token() {
|
||||
return Some((region, Ok(token)));
|
||||
LexerState::Char(val) => {
|
||||
*val = Some(
|
||||
match self.chars.next() {
|
||||
Some('\\') => {
|
||||
match self.chars.next() {
|
||||
Some('0') => '\0',
|
||||
Some('n') => '\n',
|
||||
Some('t') => '\t',
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return Some(Err(LexError::InvalidChar));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return Some(Err(LexError::InvalidChar));
|
||||
}
|
||||
});
|
||||
|
||||
match self.chars.next() {
|
||||
Some('\'') => {
|
||||
if let Some(token) = state.clone().into_token() {
|
||||
return Some(Ok(token));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if let Some(c) = self.chars.next() {
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
s.push(c);
|
||||
_ => {
|
||||
return Some(Err(LexError::InvalidChar));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_ => {
|
||||
|
||||
if c.is_whitespace()
|
||||
|| *c == '('
|
||||
|| *c == ')'
|
||||
|| *c == '{'
|
||||
|| *c == '}'
|
||||
|| *c == ';'
|
||||
|| *c == '='
|
||||
|| *c == ':'
|
||||
|| *c == '.'
|
||||
|| *c == '↦'
|
||||
|| *c == '(' || *c == ')'
|
||||
|| *c == '{' || *c == '}'
|
||||
|| *c == ';' || *c == '=' || *c == ':'
|
||||
{
|
||||
// finish the current token
|
||||
|
||||
if let Some(token) = state.clone().into_token() {
|
||||
return Some((region, Ok(token)));
|
||||
return Some(Ok(token));
|
||||
}
|
||||
} else {
|
||||
// append to the current token
|
||||
|
||||
let c = self.chars.next().unwrap();
|
||||
self.position += 1;
|
||||
region.end += 1;
|
||||
|
||||
match &mut state {
|
||||
LexerState::Sym(s) => {
|
||||
|
@ -265,7 +164,7 @@ where
|
|||
if let Some(d) = c.to_digit(10) {
|
||||
*n = (*n) * 10 + d as i64;
|
||||
} else {
|
||||
return Some((region, Err(LexError::InvalidDigit)));
|
||||
return Some(Err(LexError::InvalidDigit));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -277,31 +176,11 @@ where
|
|||
}
|
||||
|
||||
if let Some(token) = state.into_token() {
|
||||
Some((region, Ok(token)))
|
||||
Some(Ok(token))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod tests {
|
||||
#[test]
|
||||
fn test_lexer() {
|
||||
let mut lexer = crate::lexer::LTIRLexer::from(
|
||||
"let var1:ℕ=123;
|
||||
let square =λx.* x x;
|
||||
|
||||
let sqrt = λx:ℝ~machine::Float64~machine::Word.(f64-sqrt x);
|
||||
let magnitude =
|
||||
λx:ℝ
|
||||
.λy:ℝ
|
||||
.sqrt (+ (* x x) (* y y));
|
||||
"
|
||||
.chars(),
|
||||
);
|
||||
|
||||
for (range, token) in lexer {
|
||||
eprintln!("[{:?}] {:?}", range, token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
174
src/main.rs
174
src/main.rs
|
@ -1,34 +1,30 @@
|
|||
use {
|
||||
std::{boxed::{Box}, ops::Deref},
|
||||
std::collections::HashMap,
|
||||
std::sync::{Arc, RwLock},
|
||||
std::{boxed::Box, ops::Deref},
|
||||
};
|
||||
|
||||
mod expr;
|
||||
mod lexer;
|
||||
mod parser;
|
||||
mod symbols;
|
||||
mod procedure_compiler;
|
||||
mod runtime;
|
||||
mod symbols;
|
||||
mod lexer;
|
||||
mod parser;
|
||||
|
||||
use crate::{
|
||||
expr::{LTExpr, Statement},
|
||||
procedure_compiler::ProcedureCompiler,
|
||||
symbols::Scope,
|
||||
symbols::{Scope},
|
||||
procedure_compiler::ProcedureCompiler
|
||||
};
|
||||
|
||||
fn compile(
|
||||
scope: &Arc<RwLock<Scope>>,
|
||||
name: &str,
|
||||
source: &str,
|
||||
) -> Vec<tisc::assembler::AssemblyWord> {
|
||||
fn compile(scope: &Arc<RwLock<Scope>>, name: &str, source: &str) -> Vec< tisc::assembler::AssemblyWord > {
|
||||
ProcedureCompiler::new(scope)
|
||||
.compile(
|
||||
&parser::parse_expr(
|
||||
&scope.read().unwrap().typectx,
|
||||
&mut lexer::LTIRLexer::from(source.chars().peekable()).peekable(),
|
||||
)
|
||||
.expect("syntax error"),
|
||||
&mut lexer::LTIRLexer::from(
|
||||
source.chars().peekable()
|
||||
).peekable()
|
||||
).expect("syntax error")
|
||||
)
|
||||
.into_asm(&name.into())
|
||||
}
|
||||
|
@ -44,134 +40,72 @@ fn main() {
|
|||
|
||||
/* define type of the symbol
|
||||
*/
|
||||
main_scope.write().unwrap().declare_static_parse(
|
||||
"hello-string",
|
||||
"<Seq Char
|
||||
main_scope.write().unwrap()
|
||||
.declare_static_parse(
|
||||
"hello-string",
|
||||
"<Seq Char
|
||||
~Ascii
|
||||
~machine::Word>
|
||||
~<NullTerminatedSeq machine::Word>",
|
||||
);
|
||||
~<NullTerminatedSeq machine::Word>"
|
||||
);
|
||||
|
||||
main_scope.write().unwrap().declare_static_parse(
|
||||
"pfxstr",
|
||||
"<Seq Char
|
||||
main_scope.write().unwrap()
|
||||
.declare_static_parse(
|
||||
"pfxstr",
|
||||
"<Seq Char
|
||||
~Ascii
|
||||
~machine::Word>
|
||||
~<LengthPrefixedSeq machine::Word>",
|
||||
);
|
||||
~<LengthPrefixedSeq machine::Word>"
|
||||
);
|
||||
|
||||
/* link assembly-program to symbols
|
||||
*/
|
||||
linker.add_procedure(
|
||||
linker.add_procedure("main", compile(&main_scope,
|
||||
"main",
|
||||
compile(
|
||||
&main_scope,
|
||||
"main",
|
||||
"{
|
||||
let print-nullterm =
|
||||
λ str : <Ref <Seq Char~Ascii~machine::Word>>
|
||||
~ <Ref <NullTerminatedArray machine::Word>>
|
||||
~ machine::Address
|
||||
~ machine::Word
|
||||
.
|
||||
{
|
||||
while (@ str) {
|
||||
emit (@ str);
|
||||
! str (i+ str 1);
|
||||
}
|
||||
};
|
||||
"{
|
||||
let print-nullterm = λstr {
|
||||
while (@ str) {
|
||||
emit (@ str);
|
||||
! str (i+ str 1);
|
||||
}
|
||||
};
|
||||
|
||||
let print-len =
|
||||
λ len : ℤ_2^64
|
||||
~ machine::UInt64
|
||||
~ machine::Word
|
||||
.
|
||||
λ str : <Ref <Seq Char~Ascii~machine::Word>>
|
||||
~ <Ref <Array machine::Word>>
|
||||
~ machine::Address
|
||||
~ machine::Word
|
||||
.
|
||||
{
|
||||
let end = (i+ str len);
|
||||
while (i- str end) {
|
||||
emit (@ str);
|
||||
! str (i+ str 1);
|
||||
}
|
||||
};
|
||||
|
||||
let print-lenprefix =
|
||||
λ str : <Ref <Seq Char~Ascii~machine::Word>>
|
||||
~ <Ref <LenPrefixArray machine::Word>>
|
||||
~ <Ref <Struct
|
||||
<len ℤ_2^64
|
||||
~machine::UInt64
|
||||
~machine::Word>
|
||||
<data <Array machine::Word>>
|
||||
>>
|
||||
~ machine::Address
|
||||
~ machine::Word
|
||||
.
|
||||
{
|
||||
let print-lenprefix = λstr {
|
||||
let len = (@ str);
|
||||
! str (i+ str 1);
|
||||
print-len len str;
|
||||
let end = (i+ str len);
|
||||
while (i- str end) {
|
||||
emit (@ str);
|
||||
! str (i+ str 1);
|
||||
}
|
||||
};
|
||||
|
||||
let hello = λ.{
|
||||
let hello = λ _ {
|
||||
print-nullterm hello-string;
|
||||
print-lenprefix pfxstr;
|
||||
|
||||
let isquare = λx:ℤ. i* x x;
|
||||
let imagnitude2 = λx:ℤ.λy:ℤ. i+ (isquare x) (isquare y);
|
||||
let factorial = λn:ℤ.
|
||||
if( n ){ i* n (factorial (i- n 1)); }
|
||||
else { 1; };
|
||||
|
||||
factorial 20;
|
||||
|
||||
if ( i- (imagnitude2 10 20) 500 ) {
|
||||
emit '?';
|
||||
} else {
|
||||
emit '!';
|
||||
};
|
||||
|
||||
emit '\n';
|
||||
emit (i+ '0' (isquare 3));
|
||||
emit '\n';
|
||||
};
|
||||
let isquare = λx (i* x x);
|
||||
|
||||
hello;
|
||||
}",
|
||||
),
|
||||
);
|
||||
hello 'X';
|
||||
emit '\n';
|
||||
emit (i+ '0' (isquare 3));
|
||||
emit '\n';
|
||||
}"));
|
||||
|
||||
linker.add_static(
|
||||
"hello-string",
|
||||
linker.add_static("hello-string",
|
||||
"Hallo Welt!\n\0"
|
||||
.chars()
|
||||
.map(|c| (c as u8) as tisc::VM_Word)
|
||||
.collect(),
|
||||
.collect());
|
||||
|
||||
linker.add_static("pfxstr",
|
||||
vec![ 3, 'a' as tisc::VM_Word, 'b' as tisc::VM_Word, 'c' as tisc::VM_Word, 'd' as tisc::VM_Word ]
|
||||
);
|
||||
|
||||
linker.add_static(
|
||||
"pfxstr",
|
||||
vec![
|
||||
3,
|
||||
'a' as tisc::VM_Word,
|
||||
'b' as tisc::VM_Word,
|
||||
'c' as tisc::VM_Word,
|
||||
'd' as tisc::VM_Word,
|
||||
],
|
||||
);
|
||||
let main_addr = linker.get_link_addr(&"main".into()).expect("'main' not linked");
|
||||
vm.load( linker.link_total().expect("could not link") );
|
||||
vm.execute( main_addr );
|
||||
|
||||
let main_addr = linker
|
||||
.get_link_addr(&"main".into())
|
||||
.expect("'main' not linked");
|
||||
vm.load(linker.link_total().expect("could not link"));
|
||||
vm.execute(main_addr);
|
||||
|
||||
eprintln!(
|
||||
"\n====\nVM execution finished\ndatastack = {:?}\n====",
|
||||
vm.data_stack
|
||||
);
|
||||
eprintln!("\n====\nVM execution finished\ndatastack = {:?}\n====", vm.data_stack);
|
||||
}
|
||||
|
||||
|
|
264
src/parser.rs
264
src/parser.rs
|
@ -1,12 +1,9 @@
|
|||
use {
|
||||
std::iter::Peekable,
|
||||
crate::{
|
||||
expr::{LTExpr, Statement, TypeError, TypeTag},
|
||||
lexer::{LTIRLexer, LTIRToken, LexError},
|
||||
},
|
||||
std::{
|
||||
iter::Peekable,
|
||||
sync::{Arc, RwLock},
|
||||
},
|
||||
expr::{LTExpr, Statement}
|
||||
}
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
@ -14,72 +11,47 @@ pub enum ParseError {
|
|||
LexError(LexError),
|
||||
UnexpectedClose,
|
||||
UnexpectedEnd,
|
||||
UnexpectedToken,
|
||||
UnexpectedToken
|
||||
}
|
||||
|
||||
pub fn parse_expect<It>(
|
||||
tokens: &mut Peekable<LTIRLexer<It>>,
|
||||
expected_token: LTIRToken,
|
||||
) -> Result<(), ParseError>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
expected_token: LTIRToken
|
||||
) -> Result< (), ParseError >
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
match tokens.next() {
|
||||
Some((region, Ok(t))) => {
|
||||
Some(Ok(t)) => {
|
||||
if t == expected_token {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ParseError::UnexpectedToken)
|
||||
}
|
||||
}
|
||||
Some((region, Err(err))) => Err(ParseError::LexError(err)),
|
||||
None => Err(ParseError::UnexpectedEnd),
|
||||
},
|
||||
Some(Err(err)) => Err(ParseError::LexError(err)),
|
||||
None => Err(ParseError::UnexpectedEnd)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_symbol<It>(tokens: &mut Peekable<LTIRLexer<It>>) -> Result<String, ParseError>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
pub fn parse_symbol<It>(
|
||||
tokens: &mut Peekable<LTIRLexer<It>>
|
||||
) -> Result< String, ParseError >
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
match tokens.next() {
|
||||
Some((region, Ok(LTIRToken::Symbol(name)))) => Ok(name),
|
||||
Some((region, Ok(_))) => Err(ParseError::UnexpectedToken),
|
||||
Some((region, Err(err))) => Err(ParseError::LexError(err)),
|
||||
Some(Ok(LTIRToken::Symbol(name))) => Ok(name),
|
||||
Some(Ok(_)) => Err(ParseError::UnexpectedToken),
|
||||
Some(Err(err)) => Err(ParseError::LexError(err)),
|
||||
None => Err(ParseError::UnexpectedEnd),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_type_tag<It>(
|
||||
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
|
||||
tokens: &mut Peekable<LTIRLexer<It>>,
|
||||
) -> Option<TypeTag>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
{
|
||||
if let Some((region, peektok)) = tokens.peek().clone() {
|
||||
match peektok.clone() {
|
||||
Ok(LTIRToken::AssignType(typeterm_str)) => {
|
||||
tokens.next();
|
||||
match typectx.write().unwrap().parse(typeterm_str.as_str()) {
|
||||
Ok(typeterm) => Some(Ok(typeterm)),
|
||||
Err(parse_error) => Some(Err(TypeError::ParseError(parse_error))),
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_statement<It>(
|
||||
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
|
||||
tokens: &mut Peekable<LTIRLexer<It>>,
|
||||
) -> Result<crate::expr::Statement, ParseError>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
tokens: &mut Peekable<LTIRLexer<It>>
|
||||
) -> Result< crate::expr::Statement, ParseError >
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
if let Some((region, peektok)) = tokens.peek() {
|
||||
if let Some(peektok) = tokens.peek() {
|
||||
match peektok {
|
||||
Ok(LTIRToken::Symbol(sym)) => {
|
||||
match sym.as_str() {
|
||||
|
@ -87,57 +59,55 @@ where
|
|||
tokens.next();
|
||||
// todo accept address-expression instead of symbol
|
||||
let name = parse_symbol(tokens)?;
|
||||
let val_expr = parse_expr(typectx, tokens)?;
|
||||
let val_expr = parse_expr(tokens)?;
|
||||
let _ = parse_expect(tokens, LTIRToken::StatementSep)?;
|
||||
|
||||
Ok(Statement::Assignment {
|
||||
var_id: name,
|
||||
val_expr,
|
||||
val_expr
|
||||
})
|
||||
}
|
||||
"let" => {
|
||||
tokens.next();
|
||||
let name = parse_symbol(tokens)?;
|
||||
let typ = parse_type_tag(typectx, tokens);
|
||||
let _ = parse_expect(tokens, LTIRToken::AssignValue);
|
||||
let val_expr = parse_expr(typectx, tokens)?;
|
||||
let val_expr = parse_expr(tokens)?;
|
||||
let _ = parse_expect(tokens, LTIRToken::StatementSep)?;
|
||||
|
||||
Ok(Statement::LetAssign {
|
||||
typ,
|
||||
var_id: name,
|
||||
val_expr,
|
||||
val_expr
|
||||
})
|
||||
}
|
||||
"while" => {
|
||||
tokens.next();
|
||||
let _ = parse_expect(tokens, LTIRToken::ExprOpen)?;
|
||||
let cond = parse_expr(typectx, tokens)?;
|
||||
let cond = parse_expr(tokens)?;
|
||||
let _ = parse_expect(tokens, LTIRToken::ExprClose)?;
|
||||
Ok(Statement::WhileLoop {
|
||||
condition: cond,
|
||||
body: parse_block(typectx, tokens)?,
|
||||
body: parse_block(tokens)?
|
||||
})
|
||||
}
|
||||
"return" => {
|
||||
tokens.next();
|
||||
let expr = parse_expr(typectx, tokens)?;
|
||||
let expr = parse_expr(tokens)?;
|
||||
let _ = parse_expect(tokens, LTIRToken::StatementSep)?;
|
||||
Ok(Statement::Return(parse_expr(typectx, tokens)?))
|
||||
Ok(Statement::Return(parse_expr(tokens)?))
|
||||
}
|
||||
_ => {
|
||||
let expr = parse_expr(typectx, tokens)?;
|
||||
let expr = parse_expr(tokens)?;
|
||||
let _ = parse_expect(tokens, LTIRToken::StatementSep)?;
|
||||
Ok(Statement::Expr(expr))
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(_) => {
|
||||
let expr = parse_expr(typectx, tokens)?;
|
||||
let expr = parse_expr(tokens)?;
|
||||
let _ = parse_expect(tokens, LTIRToken::StatementSep)?;
|
||||
Ok(Statement::Expr(expr))
|
||||
}
|
||||
Err(err) => Err(ParseError::LexError(err.clone())),
|
||||
},
|
||||
Err(err) => Err(ParseError::LexError(err.clone()))
|
||||
}
|
||||
} else {
|
||||
Err(ParseError::UnexpectedEnd)
|
||||
|
@ -145,27 +115,21 @@ where
|
|||
}
|
||||
|
||||
pub fn parse_block<It>(
|
||||
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
|
||||
tokens: &mut Peekable<LTIRLexer<It>>,
|
||||
) -> Result<Vec<Statement>, ParseError>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
tokens: &mut Peekable<LTIRLexer<It>>
|
||||
) -> Result< Vec<Statement>, ParseError >
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
let _ = parse_expect(tokens, LTIRToken::BlockOpen)?;
|
||||
|
||||
let mut statements = Vec::new();
|
||||
while let Some((region, peektok)) = tokens.peek() {
|
||||
while let Some(peektok) = tokens.peek() {
|
||||
match peektok {
|
||||
Ok(LTIRToken::BlockClose) => {
|
||||
tokens.next();
|
||||
return Ok(statements);
|
||||
}
|
||||
Ok(_) => {
|
||||
statements.push(parse_statement(typectx, tokens)?);
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(ParseError::LexError(err.clone()));
|
||||
return Ok(statements)
|
||||
}
|
||||
Ok(_) => { statements.push( parse_statement(tokens)? ); }
|
||||
Err(err) => { return Err(ParseError::LexError(err.clone())); }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -173,47 +137,51 @@ where
|
|||
}
|
||||
|
||||
pub fn parse_atom<It>(
|
||||
tokens: &mut Peekable<LTIRLexer<It>>,
|
||||
) -> Result<crate::expr::LTExpr, ParseError>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
tokens: &mut Peekable<LTIRLexer<It>>
|
||||
) -> Result< crate::expr::LTExpr, ParseError >
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
match tokens.next() {
|
||||
Some((region, Ok(LTIRToken::Symbol(sym)))) => Ok(LTExpr::symbol(sym.as_str())),
|
||||
Some((region, Ok(LTIRToken::Char(c)))) => Ok(LTExpr::lit_uint(c as u64)),
|
||||
Some((region, Ok(LTIRToken::Num(n)))) => Ok(LTExpr::lit_uint(n as u64)),
|
||||
Some((region, Ok(_))) => Err(ParseError::UnexpectedToken),
|
||||
Some((region, Err(err))) => Err(ParseError::LexError(err)),
|
||||
None => Err(ParseError::UnexpectedEnd),
|
||||
Some(Ok(LTIRToken::Symbol(sym))) => {
|
||||
Ok(LTExpr::symbol(sym.as_str()))
|
||||
}
|
||||
Some(Ok(LTIRToken::Char(c))) => {
|
||||
Ok(LTExpr::lit_uint(c as u64))
|
||||
}
|
||||
Some(Ok(LTIRToken::Num(n))) => {
|
||||
Ok(LTExpr::lit_uint(n as u64))
|
||||
}
|
||||
Some(Ok(_)) => {
|
||||
Err(ParseError::UnexpectedToken)
|
||||
}
|
||||
Some(Err(err)) => {
|
||||
Err(ParseError::LexError(err))
|
||||
}
|
||||
None => {
|
||||
Err(ParseError::UnexpectedEnd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_expr<It>(
|
||||
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
|
||||
tokens: &mut Peekable<LTIRLexer<It>>,
|
||||
) -> Result<crate::expr::LTExpr, ParseError>
|
||||
where
|
||||
It: Iterator<Item = char>,
|
||||
tokens: &mut Peekable<LTIRLexer<It>>
|
||||
) -> Result< crate::expr::LTExpr, ParseError >
|
||||
where It: Iterator<Item = char>
|
||||
{
|
||||
let mut children = Vec::new();
|
||||
|
||||
while let Some((region, tok)) = tokens.peek() {
|
||||
while let Some(tok) = tokens.peek() {
|
||||
match tok {
|
||||
Ok(LTIRToken::Lambda) => {
|
||||
if children.len() == 0 {
|
||||
tokens.next();
|
||||
let name = parse_symbol(tokens)?;
|
||||
let body = parse_expr(tokens)?;
|
||||
|
||||
let mut args = Vec::new();
|
||||
while let Some((region, Ok(LTIRToken::Symbol(_)))) = tokens.peek() {
|
||||
args.push((parse_symbol(tokens)?, parse_type_tag(typectx, tokens)));
|
||||
}
|
||||
|
||||
let _ = parse_expect(tokens, LTIRToken::LambdaBody);
|
||||
let body = parse_expr(typectx, tokens)?;
|
||||
|
||||
return Ok(LTExpr::Abstraction {
|
||||
args,
|
||||
body: Box::new(body),
|
||||
return Ok(LTExpr::Abstraction{
|
||||
arg_id: name,
|
||||
arg_type: None,
|
||||
val_expr: Box::new(body)
|
||||
});
|
||||
} else {
|
||||
return Err(ParseError::UnexpectedToken);
|
||||
|
@ -221,7 +189,7 @@ where
|
|||
}
|
||||
Ok(LTIRToken::ExprOpen) => {
|
||||
tokens.next();
|
||||
while let Some((region, peektok)) = tokens.peek() {
|
||||
while let Some(peektok) = tokens.peek() {
|
||||
match peektok {
|
||||
Ok(LTIRToken::ExprClose) => {
|
||||
tokens.next();
|
||||
|
@ -229,66 +197,56 @@ where
|
|||
}
|
||||
_ => {}
|
||||
}
|
||||
children.push(parse_expr(typectx, tokens)?);
|
||||
}
|
||||
}
|
||||
Ok(LTIRToken::ExprClose) => {
|
||||
break;
|
||||
}
|
||||
Ok(LTIRToken::BlockOpen) => {
|
||||
children.push(LTExpr::block(parse_block(typectx, tokens)?));
|
||||
}
|
||||
Ok(LTIRToken::BlockClose) => {
|
||||
break;
|
||||
}
|
||||
Ok(LTIRToken::StatementSep) => {
|
||||
break;
|
||||
}
|
||||
Ok(LTIRToken::Symbol(name)) => match name.as_str() {
|
||||
"if" => {
|
||||
tokens.next();
|
||||
let _ = parse_expect(tokens, LTIRToken::ExprOpen)?;
|
||||
let cond = parse_expr(typectx, tokens)?;
|
||||
let _ = parse_expect(tokens, LTIRToken::ExprClose)?;
|
||||
let if_expr = LTExpr::block(parse_block(typectx, tokens)?);
|
||||
let mut else_expr = LTExpr::block(vec![]);
|
||||
|
||||
if let Some((region, peektok)) = tokens.peek() {
|
||||
if let Ok(LTIRToken::Symbol(name)) = peektok {
|
||||
if name == "else" {
|
||||
tokens.next();
|
||||
else_expr = parse_expr(typectx, tokens)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
children.push(LTExpr::Branch {
|
||||
condition: Box::new(cond),
|
||||
if_expr: Box::new(if_expr),
|
||||
else_expr: Box::new(else_expr),
|
||||
});
|
||||
}
|
||||
name => {
|
||||
children.push(parse_atom(tokens)?);
|
||||
children.push(parse_expr(tokens)?);
|
||||
}
|
||||
},
|
||||
Ok(atom) => {
|
||||
children.push(parse_atom(tokens)?);
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(ParseError::LexError(err.clone()));
|
||||
Ok(LTIRToken::ExprClose) => { break; }
|
||||
Ok(LTIRToken::BlockOpen) => { children.push( LTExpr::block(parse_block(tokens)?)); }
|
||||
Ok(LTIRToken::BlockClose) => { break; }
|
||||
Ok(LTIRToken::StatementSep) => { break; }
|
||||
Ok(LTIRToken::Symbol(name)) => {
|
||||
match name.as_str() {
|
||||
"if" => {
|
||||
tokens.next();
|
||||
let _ = parse_expect(tokens, LTIRToken::ExprOpen)?;
|
||||
let cond = parse_expr(tokens)?;
|
||||
let _ = parse_expect(tokens, LTIRToken::ExprClose)?;
|
||||
let if_expr = LTExpr::block(parse_block(tokens)?);
|
||||
let mut else_expr = LTExpr::block(vec![]);
|
||||
|
||||
if let Some(peektok) = tokens.peek() {
|
||||
if let Ok(LTIRToken::Symbol(name)) = peektok {
|
||||
if name == "else" {
|
||||
tokens.next();
|
||||
else_expr = parse_expr(tokens)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
children.push(LTExpr::Branch{
|
||||
condition: Box::new(cond),
|
||||
if_expr: Box::new(if_expr),
|
||||
else_expr: Box::new(else_expr)
|
||||
});
|
||||
}
|
||||
name => {
|
||||
children.push(parse_atom(tokens)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(atom) => { children.push(parse_atom(tokens)?); }
|
||||
Err(err) => { return Err(ParseError::LexError(err.clone())); }
|
||||
}
|
||||
}
|
||||
|
||||
if children.len() > 0 {
|
||||
let head = children.remove(0);
|
||||
Ok(LTExpr::Application {
|
||||
typ: None,
|
||||
head: Box::new(head),
|
||||
body: children,
|
||||
body: children
|
||||
})
|
||||
} else {
|
||||
Err(ParseError::UnexpectedEnd)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,13 +1,17 @@
|
|||
|
||||
use {
|
||||
std::{
|
||||
sync::{Arc, RwLock},
|
||||
ops::Deref,
|
||||
},
|
||||
tisc::{
|
||||
assembler::AssemblyWord,
|
||||
linker::LinkAddr
|
||||
},
|
||||
crate::{
|
||||
expr::{LTExpr, Statement},
|
||||
symbols::{Scope, SymbolDef},
|
||||
},
|
||||
std::{
|
||||
ops::Deref,
|
||||
sync::{Arc, RwLock},
|
||||
},
|
||||
tisc::{assembler::AssemblyWord, linker::LinkAddr},
|
||||
symbols::{Scope, SymbolDef}
|
||||
}
|
||||
};
|
||||
|
||||
pub struct ProcedureCompiler {
|
||||
|
@ -27,31 +31,27 @@ impl ProcedureCompiler {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn into_asm(mut self, proc_symbol: &String) -> Vec<tisc::assembler::AssemblyWord> {
|
||||
pub fn into_asm(mut self, proc_symbol: &String) -> Vec< tisc::assembler::AssemblyWord > {
|
||||
let data_frame_size = self.symbols.read().unwrap().get_frame_size() as i64;
|
||||
|
||||
let body = self.asm.build();
|
||||
self.linker.add_procedure("__procedure_body__", body);
|
||||
let body_addr = self
|
||||
.linker
|
||||
.get_link_addr(&"__procedure_body__".into())
|
||||
.unwrap();
|
||||
let subroutines = self
|
||||
.linker
|
||||
.link_relative(&"__subroutines__".into())
|
||||
.expect("link error");
|
||||
let body_addr = self.linker.get_link_addr(&"__procedure_body__".into()).unwrap();
|
||||
let subroutines = self.linker.link_relative(&"__subroutines__".into()).expect("link error");
|
||||
|
||||
let mut entry = tisc::Assembler::new();
|
||||
if data_frame_size > 0 {
|
||||
entry = entry.lit(data_frame_size).call("data-frame-alloc");
|
||||
entry = entry
|
||||
.lit(data_frame_size)
|
||||
.call("data-frame-alloc");
|
||||
}
|
||||
entry = entry.call_symbol(LinkAddr::Relative {
|
||||
symbol: "__subroutines__".into(),
|
||||
offset: body_addr,
|
||||
});
|
||||
entry = entry
|
||||
.call_symbol( LinkAddr::Relative{ symbol: "__subroutines__".into(), offset: body_addr });
|
||||
|
||||
if data_frame_size > 0 {
|
||||
entry = entry.lit(data_frame_size).call("data-frame-drop");
|
||||
entry = entry
|
||||
.lit(data_frame_size)
|
||||
.call("data-frame-drop");
|
||||
}
|
||||
|
||||
let mut superlink = tisc::Linker::new();
|
||||
|
@ -59,12 +59,12 @@ impl ProcedureCompiler {
|
|||
superlink.add_procedure("__subroutines__", subroutines);
|
||||
|
||||
let bytecode = superlink.link_relative(proc_symbol).expect("link error");
|
||||
/*
|
||||
eprintln!("\n\n{}:", proc_symbol);
|
||||
for (i,w) in tisc::assembler::disassemble(&bytecode).iter().enumerate() {
|
||||
eprintln!("{}:\t\t{}", i, w);
|
||||
}
|
||||
*/
|
||||
/*
|
||||
eprintln!("\n\n{}:", proc_symbol);
|
||||
for (i,w) in tisc::assembler::disassemble(&bytecode).iter().enumerate() {
|
||||
eprintln!("{}:\t\t{}", i, w);
|
||||
}
|
||||
*/
|
||||
bytecode
|
||||
}
|
||||
|
||||
|
@ -74,82 +74,84 @@ impl ProcedureCompiler {
|
|||
|
||||
pub fn compile_statement(mut self, statement: &Statement) -> Self {
|
||||
match statement {
|
||||
Statement::Assignment { var_id, val_expr } => {
|
||||
Statement::Assignment{ var_id, val_expr } => {
|
||||
self = self.compile(val_expr);
|
||||
|
||||
match self.symbols.read().unwrap().get(var_id) {
|
||||
Some(SymbolDef::FrameRef { typ, stack_ref }) => {
|
||||
self.asm = self.asm.lit(stack_ref).call("data-frame-set");
|
||||
Some(SymbolDef::FrameRef{ typ, stack_ref }) => {
|
||||
self.asm = self.asm
|
||||
.lit(stack_ref)
|
||||
.call("data-frame-set");
|
||||
}
|
||||
Some(SymbolDef::StaticRef { typ, link_addr }) => {
|
||||
self.asm = self
|
||||
.asm
|
||||
.static_ref(var_id.as_str())
|
||||
.inst(tisc::VM_Instruction::Store);
|
||||
Some(SymbolDef::StaticRef{ typ, link_addr }) => {
|
||||
self.asm = self.asm
|
||||
.static_ref( var_id.as_str() )
|
||||
.inst( tisc::VM_Instruction::Store );
|
||||
}
|
||||
Some(SymbolDef::Procedure {
|
||||
in_types,
|
||||
out_types,
|
||||
link_addr,
|
||||
}) => {
|
||||
self.asm = self
|
||||
.asm
|
||||
.call(var_id.as_str())
|
||||
.inst(tisc::VM_Instruction::Store);
|
||||
Some(SymbolDef::Procedure{ in_types, out_types, link_addr }) => {
|
||||
self.asm = self.asm
|
||||
.call( var_id.as_str() )
|
||||
.inst( tisc::VM_Instruction::Store );
|
||||
}
|
||||
None => {
|
||||
eprintln!("cannot assign undefined symbol '{}'!", var_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::LetAssign {
|
||||
typ,
|
||||
var_id,
|
||||
val_expr,
|
||||
} => match val_expr {
|
||||
LTExpr::Abstraction { args: _, body: _ } => {
|
||||
self.symbols
|
||||
.write()
|
||||
.unwrap()
|
||||
.declare_proc(var_id.clone(), vec![], vec![]);
|
||||
let lambda_procedure = ProcedureCompiler::new(&self.symbols)
|
||||
.compile(val_expr)
|
||||
.into_asm(var_id);
|
||||
Statement::LetAssign{ var_id, val_expr } => {
|
||||
match val_expr {
|
||||
LTExpr::Abstraction { arg_id:_, arg_type:_, val_expr:_ } => {
|
||||
self.symbols.write().unwrap()
|
||||
.declare_proc(
|
||||
var_id.clone(),
|
||||
vec![],vec![]
|
||||
);
|
||||
let lambda_procedure =
|
||||
ProcedureCompiler::new(&self.symbols)
|
||||
.compile( val_expr )
|
||||
.into_asm( var_id );
|
||||
|
||||
self.linker.add_procedure(var_id, lambda_procedure);
|
||||
self.linker.add_procedure(
|
||||
var_id,
|
||||
lambda_procedure
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
self.symbols.write().unwrap()
|
||||
.declare_var(
|
||||
var_id.clone(),
|
||||
laddertypes::TypeTerm::unit()
|
||||
);
|
||||
self = self.compile_statement(
|
||||
&Statement::Assignment {
|
||||
var_id: var_id.clone(),
|
||||
val_expr: val_expr.clone()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.symbols
|
||||
.write()
|
||||
.unwrap()
|
||||
.declare_var(var_id.clone(), laddertypes::TypeTerm::unit());
|
||||
self = self.compile_statement(&Statement::Assignment {
|
||||
var_id: var_id.clone(),
|
||||
val_expr: val_expr.clone(),
|
||||
});
|
||||
}
|
||||
},
|
||||
}
|
||||
Statement::WhileLoop { condition, body } => {
|
||||
let asm = self.asm;
|
||||
|
||||
self.asm = tisc::Assembler::new();
|
||||
self = self.compile(condition);
|
||||
self = self.compile( condition );
|
||||
let cond_asm = self.asm;
|
||||
|
||||
self.asm = tisc::Assembler::new();
|
||||
for statement in body.into_iter() {
|
||||
self = self.compile_statement(statement);
|
||||
self = self.compile_statement( statement );
|
||||
}
|
||||
let body_asm = self.asm;
|
||||
|
||||
self.asm = asm;
|
||||
self.asm = self.asm.while_loop(cond_asm, body_asm);
|
||||
}
|
||||
Statement::Expr(expr) => {
|
||||
self = self.compile(expr);
|
||||
Statement::Expr( expr ) => {
|
||||
self = self.compile( expr );
|
||||
}
|
||||
Statement::Return(expr) => {
|
||||
self = self.compile(expr);
|
||||
Statement::Return( expr ) => {
|
||||
self = self.compile( expr );
|
||||
}
|
||||
}
|
||||
self
|
||||
|
@ -157,64 +159,58 @@ impl ProcedureCompiler {
|
|||
|
||||
pub fn compile(mut self, expr: <Expr) -> Self {
|
||||
match expr {
|
||||
LTExpr::Symbol { typ, symbol } => match self.symbols.read().unwrap().get(symbol) {
|
||||
Some(SymbolDef::FrameRef { typ, stack_ref }) => {
|
||||
self.asm = self.asm.lit(stack_ref).call("data-frame-get");
|
||||
LTExpr::Symbol { typ, symbol } => {
|
||||
match self.symbols.read().unwrap().get(symbol) {
|
||||
Some(SymbolDef::FrameRef{ typ, stack_ref }) => {
|
||||
self.asm = self.asm
|
||||
.lit( stack_ref )
|
||||
.call("data-frame-get");
|
||||
}
|
||||
Some(SymbolDef::StaticRef{ typ, link_addr }) => {
|
||||
self.asm = self.asm.static_ref( symbol.as_str() );
|
||||
}
|
||||
Some(SymbolDef::Procedure{ in_types, out_types, link_addr }) => {
|
||||
self.asm = self.asm.call( symbol.as_str() );
|
||||
}
|
||||
None => {
|
||||
eprintln!("undefined symbol '{}'!", symbol);
|
||||
}
|
||||
}
|
||||
Some(SymbolDef::StaticRef { typ, link_addr }) => {
|
||||
self.asm = self.asm.static_ref(symbol.as_str());
|
||||
}
|
||||
Some(SymbolDef::Procedure {
|
||||
in_types,
|
||||
out_types,
|
||||
link_addr,
|
||||
}) => {
|
||||
self.asm = self.asm.call(symbol.as_str());
|
||||
}
|
||||
None => {
|
||||
eprintln!("undefined symbol '{}'!", symbol);
|
||||
}
|
||||
},
|
||||
LTExpr::Literal { typ, val } => {
|
||||
self.asm = self.asm.lit(*val);
|
||||
}
|
||||
LTExpr::Application { typ, head, body } => {
|
||||
LTExpr::Literal { typ, val } => {
|
||||
self.asm = self.asm.lit( *val );
|
||||
}
|
||||
LTExpr::Application { head, body } => {
|
||||
for arg in body.iter().rev() {
|
||||
self = self.compile(arg);
|
||||
}
|
||||
self = self.compile(head);
|
||||
}
|
||||
LTExpr::Abstraction { args, body } => {
|
||||
for (arg_name, arg_type) in args.iter() {
|
||||
if let Some(Ok(typeterm)) = arg_type {
|
||||
let id = self
|
||||
.symbols
|
||||
.write()
|
||||
.unwrap()
|
||||
.declare_var(arg_name.clone(), typeterm.clone());
|
||||
self.asm = self.asm.lit(id).call("data-frame-set");
|
||||
} else {
|
||||
eprintln!("invalid type {:?} for argument {}", arg_type, arg_name);
|
||||
}
|
||||
}
|
||||
self = self.compile(body);
|
||||
LTExpr::Abstraction { arg_id: arg_name, arg_type, val_expr } => {
|
||||
let id = self.symbols
|
||||
.write().unwrap()
|
||||
.declare_var(
|
||||
arg_name.clone(),
|
||||
laddertypes::TypeTerm::unit());
|
||||
|
||||
self.asm = self.asm
|
||||
.lit( id )
|
||||
.call("data-frame-set");
|
||||
|
||||
self = self.compile(val_expr);
|
||||
}
|
||||
LTExpr::Branch {
|
||||
condition,
|
||||
if_expr,
|
||||
else_expr,
|
||||
} => {
|
||||
LTExpr::Branch { condition, if_expr, else_expr } => {
|
||||
self = self.compile(condition);
|
||||
|
||||
let asm = self.asm;
|
||||
self.asm = tisc::Assembler::new();
|
||||
self = self.compile(if_expr);
|
||||
self = self.compile( if_expr );
|
||||
let if_asm = self.asm;
|
||||
self.asm = tisc::Assembler::new();
|
||||
self = self.compile(else_expr);
|
||||
self = self.compile( else_expr );
|
||||
let else_asm = self.asm;
|
||||
self.asm = asm;
|
||||
self.asm = self.asm.branch(if_asm, else_asm);
|
||||
self.asm = self.asm.branch( if_asm, else_asm );
|
||||
}
|
||||
LTExpr::Block { statements } => {
|
||||
for s in statements.iter() {
|
||||
|
@ -225,3 +221,4 @@ impl ProcedureCompiler {
|
|||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
|
217
src/runtime.rs
217
src/runtime.rs
|
@ -1,10 +1,14 @@
|
|||
use {
|
||||
crate::{expr::LTExpr, procedure_compiler::ProcedureCompiler, symbols::Scope},
|
||||
std::sync::{Arc, RwLock},
|
||||
tisc::linker::Linker,
|
||||
crate::{
|
||||
expr::LTExpr,
|
||||
symbols::Scope,
|
||||
procedure_compiler::ProcedureCompiler
|
||||
},
|
||||
tisc::linker::Linker
|
||||
};
|
||||
|
||||
pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
|
||||
pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
|
||||
let symbols = Scope::new();
|
||||
let typectx = symbols.read().unwrap().typectx.clone();
|
||||
|
||||
|
@ -13,33 +17,26 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
|
|||
*/
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"dup",
|
||||
vec!["T"],
|
||||
vec!["T~machine::Word"],
|
||||
vec!["T~machine::Word", "T~machine::Word"],
|
||||
vec![ "T" ],
|
||||
vec![ "T~machine::Word" ],
|
||||
vec![ "T~machine::Word",
|
||||
"T~machine::Word" ]
|
||||
);
|
||||
|
||||
linker.add_procedure(
|
||||
"dup",
|
||||
tisc::Assembler::new()
|
||||
.inst(tisc::VM_Instruction::Dup)
|
||||
.build(),
|
||||
);
|
||||
linker.add_procedure("dup", tisc::Assembler::new().inst( tisc::VM_Instruction::Dup ).build());
|
||||
|
||||
|
||||
/* Put a single Ascii character on stdout
|
||||
*/
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"emit",
|
||||
vec![],
|
||||
vec!["Char~Ascii~machine::Word"],
|
||||
vec![],
|
||||
vec![ "Char~Ascii~machine::Word" ],
|
||||
vec![]
|
||||
);
|
||||
|
||||
linker.add_procedure(
|
||||
"emit",
|
||||
tisc::Assembler::new()
|
||||
.inst(tisc::VM_Instruction::Emit)
|
||||
.build(),
|
||||
);
|
||||
linker.add_procedure("emit", tisc::Assembler::new().inst( tisc::VM_Instruction::Emit ).build());
|
||||
|
||||
|
||||
/* The top two items must be native u64 integers,
|
||||
* which are replaced by their sum.
|
||||
|
@ -49,92 +46,87 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
|
|||
symbols.write().unwrap().declare_proc_parse(
|
||||
"i+",
|
||||
vec![],
|
||||
vec![
|
||||
"ℤ_2^64~machine::UInt64~machine::Word",
|
||||
"ℤ_2^64~machine::UInt64~machine::Word",
|
||||
],
|
||||
vec!["ℤ_2^64~machine::UInt64~machine::Word"],
|
||||
vec![ "ℤ_2^64~machine::UInt64~machine::Word",
|
||||
"ℤ_2^64~machine::UInt64~machine::Word" ],
|
||||
vec![ "ℤ_2^64~machine::UInt64~machine::Word" ]
|
||||
);
|
||||
|
||||
linker.add_procedure(
|
||||
"i+",
|
||||
tisc::Assembler::new()
|
||||
.inst(tisc::VM_Instruction::IntAdd)
|
||||
.build(),
|
||||
.inst( tisc::VM_Instruction::Add )
|
||||
.build()
|
||||
);
|
||||
|
||||
/* Floating-point Addition
|
||||
|
||||
/* Floating-point Additionu
|
||||
*/
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"f+",
|
||||
vec![],
|
||||
vec![
|
||||
"ℝ~machine::f64~machine::Word",
|
||||
"ℝ~machine::f64~machine::Word",
|
||||
],
|
||||
vec!["ℝ~machine::f64~machine::Word"],
|
||||
vec![ "ℝ~machine::f64~machine::Word",
|
||||
"ℝ~machine::f64~machine::Word" ],
|
||||
vec![ "ℝ~machine::f64~machine::Word" ]
|
||||
);
|
||||
|
||||
linker.add_procedure(
|
||||
"f+",
|
||||
tisc::Assembler::new()
|
||||
.inst(tisc::VM_Instruction::FltAdd)
|
||||
.build(),
|
||||
.inst( tisc::VM_Instruction::Addf )
|
||||
.build()
|
||||
);
|
||||
|
||||
|
||||
/* Integer Subtraction
|
||||
*/
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"i-",
|
||||
vec![],
|
||||
vec![
|
||||
"ℤ_2^64~machine::UInt64~machine::Word",
|
||||
"ℤ_2^64~machine::UInt64~machine::Word",
|
||||
],
|
||||
vec!["ℤ_2^64~machine::UInt64~machine::Word"],
|
||||
vec![ "ℤ_2^64~machine::UInt64~machine::Word",
|
||||
"ℤ_2^64~machine::UInt64~machine::Word" ],
|
||||
vec![ "ℤ_2^64~machine::UInt64~machine::Word" ]
|
||||
);
|
||||
linker.add_procedure(
|
||||
"i-",
|
||||
tisc::Assembler::new()
|
||||
.inst(tisc::VM_Instruction::Swap)
|
||||
.inst(tisc::VM_Instruction::BitNeg)
|
||||
.inst(tisc::VM_Instruction::BitwiseNot)
|
||||
.lit(1)
|
||||
.inst(tisc::VM_Instruction::IntAdd)
|
||||
.inst(tisc::VM_Instruction::IntAdd)
|
||||
.build(),
|
||||
.inst(tisc::VM_Instruction::Add)
|
||||
.inst(tisc::VM_Instruction::Add)
|
||||
.build()
|
||||
);
|
||||
|
||||
|
||||
/* Fetch memory address
|
||||
*/
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"@",
|
||||
symbols.write().unwrap().declare_proc_parse("@",
|
||||
vec![],
|
||||
vec!["<MutRef T~machine::Word>~machine::Address~machine::Word"],
|
||||
vec!["T~machine::Word"],
|
||||
vec![ "<MutRef T~machine::Word>~machine::Address~machine::Word" ],
|
||||
vec![ "T~machine::Word" ]
|
||||
);
|
||||
linker.add_procedure(
|
||||
"@",
|
||||
tisc::Assembler::new()
|
||||
.inst(tisc::VM_Instruction::Fetch)
|
||||
.build(),
|
||||
.inst( tisc::VM_Instruction::Fetch )
|
||||
.build()
|
||||
);
|
||||
|
||||
|
||||
/* Store to memory
|
||||
*/
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"!",
|
||||
symbols.write().unwrap().declare_proc_parse("!",
|
||||
vec![],
|
||||
vec![
|
||||
"<MutRef T~machine::Word>~machine::Address~machine::Word",
|
||||
"T~machine::Word",
|
||||
"T~machine::Word"
|
||||
],
|
||||
vec![],
|
||||
vec![]
|
||||
);
|
||||
linker.add_procedure(
|
||||
"!",
|
||||
tisc::Assembler::new()
|
||||
.inst(tisc::VM_Instruction::Store)
|
||||
.build(),
|
||||
.inst( tisc::VM_Instruction::Store )
|
||||
.build()
|
||||
);
|
||||
|
||||
/*
|
||||
|
@ -150,126 +142,133 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
|
|||
symbols.write().unwrap().declare_proc_parse(
|
||||
"i*",
|
||||
vec![],
|
||||
vec![
|
||||
"ℤ_2^64~machine::UInt64~machine::Word",
|
||||
"ℤ_2^64~machine::UInt64~machine::Word",
|
||||
],
|
||||
vec!["ℤ_2^64~machine::UInt64~machine::Word"],
|
||||
);
|
||||
vec![ "ℤ_2^64~machine::UInt64~machine::Word",
|
||||
"ℤ_2^64~machine::UInt64~machine::Word" ],
|
||||
vec![ "ℤ_2^64~machine::UInt64~machine::Word" ]);
|
||||
|
||||
linker.add_procedure(
|
||||
"i*",
|
||||
tisc::Assembler::new()
|
||||
.lit(0) // [ a b ] -- [ a b sum ]
|
||||
|
||||
.while_loop(
|
||||
// condition
|
||||
tisc::Assembler::new()
|
||||
// [ a b sum ] -- [ a b sum b ]
|
||||
.lit(2)
|
||||
.inst(tisc::VM_Instruction::Pick),
|
||||
.lit( 2 )
|
||||
.inst( tisc::VM_Instruction::Pick ),
|
||||
|
||||
// body
|
||||
tisc::Assembler::new()
|
||||
// [ a b sum ] -- [ a b sum a ]
|
||||
.lit(3)
|
||||
.inst(tisc::VM_Instruction::Pick)
|
||||
.lit( 3 )
|
||||
.inst( tisc::VM_Instruction::Pick )
|
||||
|
||||
// [ a b sum a -- a b (sum+a) ]
|
||||
.inst(tisc::VM_Instruction::IntAdd)
|
||||
.inst( tisc::VM_Instruction::Add )
|
||||
|
||||
// [ a b sum -- a sum b ]
|
||||
.inst(tisc::VM_Instruction::Swap)
|
||||
.inst( tisc::VM_Instruction::Swap )
|
||||
|
||||
// [ a sum b -- a sum b 1 ]
|
||||
.lit(1)
|
||||
.lit( 1 )
|
||||
|
||||
// [ a sum b -- a sum (b-1) ]
|
||||
.inst(tisc::VM_Instruction::Swap)
|
||||
.call("i-")
|
||||
.call( "i-" )
|
||||
|
||||
// [ a sum b -- a b sum ]
|
||||
.inst(tisc::VM_Instruction::Swap),
|
||||
.inst( tisc::VM_Instruction::Swap )
|
||||
)
|
||||
|
||||
// [ a b sum -- a sum b ]
|
||||
.lit(2)
|
||||
.inst(tisc::VM_Instruction::Roll)
|
||||
.lit(2).inst(tisc::VM_Instruction::Roll)
|
||||
// [ a sum b -- a sum ]
|
||||
.inst(tisc::VM_Instruction::Drop)
|
||||
|
||||
// [ a sum -- sum a ]
|
||||
.lit(2)
|
||||
.inst(tisc::VM_Instruction::Roll)
|
||||
.lit(2).inst(tisc::VM_Instruction::Roll)
|
||||
// [ sum a -- sum ]
|
||||
.inst(tisc::VM_Instruction::Drop)
|
||||
.build(),
|
||||
|
||||
.build()
|
||||
);
|
||||
|
||||
symbols.write().unwrap().declare_static_parse(
|
||||
"data-frame-ptr",
|
||||
"<MutRef <Seq machine::Word>>~machine::Address~machine::Word",
|
||||
"<MutRef <Seq machine::Word>>~machine::Address~machine::Word"
|
||||
);
|
||||
linker.add_static("data-frame-ptr", vec![0x1000]);
|
||||
linker.add_static("data-frame-ptr", vec![ 0x1000 ]);
|
||||
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"data-frame-set",
|
||||
vec!["T"],
|
||||
vec![
|
||||
"T~machine::Word",
|
||||
"<RefMut T~machine::Word>~LocalVariableId~machine::UInt64~machine::Word",
|
||||
],
|
||||
vec![],
|
||||
);
|
||||
vec!["T~machine::Word",
|
||||
"<RefMut T~machine::Word>~LocalVariableId~machine::UInt64~machine::Word"],
|
||||
vec![]);
|
||||
|
||||
linker.add_procedure(
|
||||
"data-frame-set",
|
||||
tisc::Assembler::new()
|
||||
.static_ref("data-frame-ptr")
|
||||
.inst(tisc::VM_Instruction::Fetch)
|
||||
.inst(tisc::VM_Instruction::IntAdd)
|
||||
.inst(tisc::VM_Instruction::Store)
|
||||
.build(),
|
||||
.inst( tisc::VM_Instruction::Fetch )
|
||||
.inst( tisc::VM_Instruction::Add )
|
||||
.inst( tisc::VM_Instruction::Store )
|
||||
.build()
|
||||
);
|
||||
|
||||
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"data-frame-get",
|
||||
vec!["T"],
|
||||
vec!["<Ref T~machine::Word>~DataFrameRef~machine::UInt64~machine::Word"],
|
||||
vec!["T~machine::Word"],
|
||||
vec!["T~machine::Word"]
|
||||
);
|
||||
linker.add_procedure(
|
||||
"data-frame-get",
|
||||
tisc::Assembler::new()
|
||||
.static_ref("data-frame-ptr")
|
||||
.inst(tisc::VM_Instruction::Fetch)
|
||||
.inst(tisc::VM_Instruction::IntAdd)
|
||||
.inst(tisc::VM_Instruction::Fetch)
|
||||
.build(),
|
||||
.inst( tisc::VM_Instruction::Fetch )
|
||||
.inst( tisc::VM_Instruction::Add )
|
||||
.inst( tisc::VM_Instruction::Fetch )
|
||||
.build()
|
||||
);
|
||||
|
||||
symbols
|
||||
.write()
|
||||
.unwrap()
|
||||
.declare_proc_parse("data-frame-alloc", vec![], vec![], vec![]);
|
||||
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"data-frame-alloc",
|
||||
vec![],
|
||||
vec![],
|
||||
vec![]);
|
||||
|
||||
linker.add_procedure(
|
||||
"data-frame-alloc",
|
||||
tisc::Assembler::new()
|
||||
.static_ref("data-frame-ptr")
|
||||
.inst(tisc::VM_Instruction::Fetch)
|
||||
.inst( tisc::VM_Instruction::Fetch )
|
||||
.inst( tisc::VM_Instruction::Swap )
|
||||
.call("i-")
|
||||
.static_ref("data-frame-ptr")
|
||||
.inst(tisc::VM_Instruction::Store)
|
||||
.build(),
|
||||
.inst( tisc::VM_Instruction::Store )
|
||||
.build()
|
||||
);
|
||||
|
||||
symbols
|
||||
.write()
|
||||
.unwrap()
|
||||
.declare_proc_parse("data-frame-drop", vec![], vec![], vec![]);
|
||||
symbols.write().unwrap().declare_proc_parse(
|
||||
"data-frame-drop",
|
||||
vec![],
|
||||
vec![],
|
||||
vec![]);
|
||||
|
||||
linker.add_procedure(
|
||||
"data-frame-drop",
|
||||
tisc::Assembler::new()
|
||||
.static_ref("data-frame-ptr")
|
||||
.inst(tisc::VM_Instruction::Fetch)
|
||||
.inst( tisc::VM_Instruction::Fetch )
|
||||
.call("i+")
|
||||
.static_ref("data-frame-ptr")
|
||||
.inst(tisc::VM_Instruction::Store)
|
||||
.build(),
|
||||
.inst( tisc::VM_Instruction::Store )
|
||||
.build()
|
||||
);
|
||||
|
||||
symbols
|
||||
}
|
||||
|
||||
|
|
191
src/symbols.rs
191
src/symbols.rs
|
@ -1,9 +1,9 @@
|
|||
use {
|
||||
crate::expr::LTExpr,
|
||||
std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, RwLock},
|
||||
},
|
||||
crate::expr::LTExpr
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
@ -14,36 +14,27 @@ pub enum SymbolDef {
|
|||
},
|
||||
StaticRef {
|
||||
typ: laddertypes::TypeTerm,
|
||||
link_addr: Option<tisc::VM_Word>,
|
||||
link_addr: Option< tisc::VM_Word >
|
||||
},
|
||||
Procedure {
|
||||
in_types: Vec<laddertypes::TypeTerm>,
|
||||
out_types: Vec<laddertypes::TypeTerm>,
|
||||
link_addr: Option<tisc::VM_Word>,
|
||||
},
|
||||
in_types: Vec< laddertypes::TypeTerm >,
|
||||
out_types: Vec< laddertypes::TypeTerm >,
|
||||
link_addr: Option< tisc::VM_Word >
|
||||
}
|
||||
}
|
||||
|
||||
impl SymbolDef {
|
||||
pub fn get_type(
|
||||
&self,
|
||||
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
|
||||
) -> laddertypes::TypeTerm {
|
||||
pub fn get_type(&self, typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>) -> laddertypes::TypeTerm {
|
||||
match self {
|
||||
SymbolDef::FrameRef { typ, stack_ref: _ } => typ.clone(),
|
||||
SymbolDef::StaticRef { typ, link_addr: _ } => typ.clone(),
|
||||
SymbolDef::Procedure {
|
||||
in_types,
|
||||
out_types,
|
||||
link_addr: _,
|
||||
} => laddertypes::TypeTerm::App(vec![
|
||||
typectx
|
||||
.write()
|
||||
.unwrap()
|
||||
.parse("Fn")
|
||||
.expect("parse typeterm"),
|
||||
laddertypes::TypeTerm::App(in_types.clone()),
|
||||
laddertypes::TypeTerm::App(out_types.clone()),
|
||||
]),
|
||||
SymbolDef::FrameRef { typ, stack_ref:_ } => typ.clone(),
|
||||
SymbolDef::StaticRef { typ, link_addr:_ } => typ.clone(),
|
||||
SymbolDef::Procedure { in_types, out_types, link_addr: _ } => {
|
||||
laddertypes::TypeTerm::App(vec![
|
||||
typectx.write().unwrap().parse("Fn").expect("parse typeterm"),
|
||||
laddertypes::TypeTerm::App( in_types.clone() ),
|
||||
laddertypes::TypeTerm::App( out_types.clone() )
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -53,7 +44,7 @@ impl SymbolDef {
|
|||
pub struct Scope {
|
||||
/* definition of runtime symbols
|
||||
*/
|
||||
symbols: HashMap<String, SymbolDef>,
|
||||
symbols: HashMap< String, SymbolDef >,
|
||||
|
||||
/* type symbols
|
||||
*/
|
||||
|
@ -66,17 +57,17 @@ pub struct Scope {
|
|||
|
||||
/* parent scope whose all
|
||||
* symbols are inherited
|
||||
*/
|
||||
parent: Option<Arc<RwLock<Scope>>>,
|
||||
*/
|
||||
parent: Option< Arc<RwLock<Scope>> >
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
pub fn new() -> Arc<RwLock<Self>> {
|
||||
Arc::new(RwLock::new(Scope {
|
||||
symbols: HashMap::new(),
|
||||
typectx: Arc::new(RwLock::new(laddertypes::dict::TypeDict::new())),
|
||||
typectx: Arc::new(RwLock::new( laddertypes::dict::TypeDict::new() )),
|
||||
frame_size: 0,
|
||||
parent: None,
|
||||
parent: None
|
||||
}))
|
||||
}
|
||||
|
||||
|
@ -99,16 +90,17 @@ impl Scope {
|
|||
}
|
||||
|
||||
pub fn get(&self, name: &str) -> Option<SymbolDef> {
|
||||
match self.symbols.get(name) {
|
||||
match self.symbols.get(name) {
|
||||
Some(def) => Some(def.clone()),
|
||||
None => {
|
||||
if let Some(parent) = self.parent.as_ref() {
|
||||
match parent.read().unwrap().get(name) {
|
||||
Some(SymbolDef::FrameRef { typ, stack_ref }) => Some(SymbolDef::FrameRef {
|
||||
typ: typ.clone(),
|
||||
stack_ref: stack_ref + self.get_frame_size() as i64,
|
||||
match parent.read().unwrap().get( name ) {
|
||||
Some(SymbolDef::FrameRef {
|
||||
typ, stack_ref
|
||||
}) => Some(SymbolDef::FrameRef {
|
||||
typ: typ.clone(), stack_ref: stack_ref + self.get_frame_size() as i64
|
||||
}),
|
||||
x => x.clone(),
|
||||
x => x.clone()
|
||||
}
|
||||
} else {
|
||||
None
|
||||
|
@ -116,28 +108,27 @@ impl Scope {
|
|||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
pub fn get_link_addr(&self, name: &str) -> Option<tisc::VM_Word> {
|
||||
match self.get(name) {
|
||||
Some(SymbolDef::Procedure{ in_types:_, out_types:_, link_addr }) => {
|
||||
link_addr
|
||||
}
|
||||
Some(SymbolDef::StaticRef { typ:_, link_addr }) => {
|
||||
link_addr
|
||||
}
|
||||
Some(SymbolDef::FrameRef { typ:_, stack_ref:_ }) => None,
|
||||
None => None
|
||||
/*
|
||||
pub fn get_link_addr(&self, name: &str) -> Option<tisc::VM_Word> {
|
||||
match self.get(name) {
|
||||
Some(SymbolDef::Procedure{ in_types:_, out_types:_, link_addr }) => {
|
||||
link_addr
|
||||
}
|
||||
Some(SymbolDef::StaticRef { typ:_, link_addr }) => {
|
||||
link_addr
|
||||
}
|
||||
Some(SymbolDef::FrameRef { typ:_, stack_ref:_ }) => None,
|
||||
None => None
|
||||
}
|
||||
*/
|
||||
}
|
||||
*/
|
||||
//<><><><><><>
|
||||
|
||||
pub fn declare_proc_parse(
|
||||
&mut self,
|
||||
pub fn declare_proc_parse(&mut self,
|
||||
name: &str,
|
||||
type_vars: Vec<&str>,
|
||||
in_types: Vec<&str>,
|
||||
out_types: Vec<&str>,
|
||||
out_types: Vec<&str>
|
||||
) {
|
||||
for v in type_vars {
|
||||
self.typectx.write().unwrap().add_varname(v.into());
|
||||
|
@ -145,86 +136,70 @@ impl Scope {
|
|||
|
||||
self.declare_proc(
|
||||
String::from(name),
|
||||
in_types
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
self.typectx
|
||||
.write()
|
||||
.unwrap()
|
||||
.parse(t)
|
||||
.expect("parse typeterm")
|
||||
})
|
||||
.collect(),
|
||||
out_types
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
self.typectx
|
||||
.write()
|
||||
.unwrap()
|
||||
.parse(t)
|
||||
.expect("parse typeterm")
|
||||
})
|
||||
.collect(),
|
||||
in_types.into_iter().map(|t| self.typectx.write().unwrap().parse(t).expect("parse typeterm")).collect(),
|
||||
out_types.into_iter().map(|t| self.typectx.write().unwrap().parse(t).expect("parse typeterm")).collect()
|
||||
);
|
||||
}
|
||||
|
||||
pub fn declare_proc(
|
||||
&mut self,
|
||||
pub fn declare_proc(&mut self,
|
||||
name: String,
|
||||
in_types: Vec<laddertypes::TypeTerm>,
|
||||
out_types: Vec<laddertypes::TypeTerm>,
|
||||
in_types: Vec< laddertypes::TypeTerm >,
|
||||
out_types: Vec< laddertypes::TypeTerm >
|
||||
) {
|
||||
self.symbols.insert(
|
||||
name,
|
||||
SymbolDef::Procedure {
|
||||
link_addr: None, //LinkAddr::Relative{ name, offset: 0 },
|
||||
in_types,
|
||||
out_types,
|
||||
},
|
||||
);
|
||||
self.symbols.insert(name, SymbolDef::Procedure {
|
||||
link_addr: None,//LinkAddr::Relative{ name, offset: 0 },
|
||||
in_types,
|
||||
out_types
|
||||
});
|
||||
}
|
||||
|
||||
//<><><><><>
|
||||
|
||||
pub fn declare_var_parse(&mut self, name: &str, typ: &str) {
|
||||
let typ = self
|
||||
.typectx
|
||||
.write()
|
||||
.unwrap()
|
||||
.parse(typ)
|
||||
.expect("parse typeterm");
|
||||
self.declare_var(String::from(name), typ);
|
||||
pub fn declare_var_parse(&mut self,
|
||||
name: &str,
|
||||
typ: &str
|
||||
) {
|
||||
let typ = self.typectx.write().unwrap().parse(typ).expect("parse typeterm");
|
||||
self.declare_var(
|
||||
String::from(name),
|
||||
typ
|
||||
);
|
||||
}
|
||||
|
||||
pub fn declare_var(&mut self, name: String, typ: laddertypes::TypeTerm) -> tisc::VM_Word {
|
||||
let stack_ref = self.frame_size as tisc::VM_Word;
|
||||
self.frame_size += 1;
|
||||
|
||||
self.symbols
|
||||
.insert(name, SymbolDef::FrameRef { typ, stack_ref });
|
||||
self.symbols.insert(name, SymbolDef::FrameRef {
|
||||
typ,
|
||||
stack_ref
|
||||
});
|
||||
|
||||
stack_ref
|
||||
}
|
||||
|
||||
//<><><><><><>
|
||||
|
||||
pub fn declare_static_parse(&mut self, name: &str, typ: &str) {
|
||||
let typ = self
|
||||
.typectx
|
||||
.write()
|
||||
.unwrap()
|
||||
.parse(typ)
|
||||
.expect("parse typeterm");
|
||||
pub fn declare_static_parse(
|
||||
&mut self,
|
||||
name: &str,
|
||||
typ: &str
|
||||
) {
|
||||
let typ = self.typectx
|
||||
.write().unwrap()
|
||||
.parse(typ).expect("parse typeterm");
|
||||
self.declare_static(String::from(name), typ);
|
||||
}
|
||||
|
||||
pub fn declare_static(&mut self, name: String, typ: laddertypes::TypeTerm) {
|
||||
self.symbols.insert(
|
||||
name,
|
||||
SymbolDef::StaticRef {
|
||||
typ,
|
||||
link_addr: None,
|
||||
},
|
||||
);
|
||||
pub fn declare_static(
|
||||
&mut self,
|
||||
name: String,
|
||||
typ: laddertypes::TypeTerm
|
||||
) {
|
||||
self.symbols.insert(name, SymbolDef::StaticRef {
|
||||
typ,
|
||||
link_addr: None
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue