Compare commits

..

No commits in common. "2b7d974851f763431a70fe7b59728c94cfabddf7" and "c9102655312f5d9824fcf9a6b2f090b46b1bb93d" have entirely different histories.

4 changed files with 279 additions and 513 deletions

View file

@ -52,7 +52,6 @@ where
It: std::iter::Iterator<Item = char>,
{
chars: std::iter::Peekable<It>,
position: usize
}
impl<It> LTIRLexer<It>
@ -71,23 +70,6 @@ where
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 )
}
}
}
@ -96,14 +78,10 @@ impl<It> Iterator for LTIRLexer<It>
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 {
@ -111,70 +89,47 @@ where
LexerState::Any => match c {
'λ' => {
self.chars.next();
self.position += 1;
region.end += 1;
return Some((region, Ok(LTIRToken::Lambda)));
return Some(Ok(LTIRToken::Lambda));
}
'.' | '↦' => {
'.' => {
self.chars.next();
self.position += 1;
region.end += 1;
return Some((region, Ok(LTIRToken::LambdaBody)));
return Some(Ok(LTIRToken::LambdaBody));
}
'(' => {
self.chars.next();
self.position += 1;
region.end += 1;
return Some((region, Ok(LTIRToken::ExprOpen)));
return Some(Ok(LTIRToken::ExprOpen));
}
')' => {
self.chars.next();
self.position += 1;
region.end += 1;
return Some((region, Ok(LTIRToken::ExprClose)));
return Some(Ok(LTIRToken::ExprClose));
}
'{' => {
self.chars.next();
self.position += 1;
region.end += 1;
return Some((region, Ok(LTIRToken::BlockOpen)));
return Some(Ok(LTIRToken::BlockOpen));
}
'}' => {
self.chars.next();
self.position += 1;
region.end += 1;
return Some((region, Ok(LTIRToken::BlockClose)));
return Some(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)));
return Some(Ok(LTIRToken::AssignValue));
}
';' => {
self.chars.next();
self.position += 1;
region.end += 1;
return Some((region, Ok(LTIRToken::StatementSep)));
return Some(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 {
@ -184,49 +139,41 @@ where
},
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)));
}
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((region, Err(LexError::InvalidChar)));
return Some(Err(LexError::InvalidChar));
}
});
match self.chars.next() {
Some('\'') => {
if let Some(token) = state.clone().into_token() {
return Some((region, Ok(token)));
return Some(Ok(token));
}
}
_ => {
return Some((region, Err(LexError::InvalidChar)));
return Some(Err(LexError::InvalidChar));
}
}
}
LexerState::TypeTerm(s) => {
if *c == '=' || *c == '.' || *c == '↦' || *c == ';' {
if *c == '=' || *c == '.' {
if let Some(token) = state.clone().into_token() {
return Some((region, Ok(token)));
return Some(Ok(token));
}
} else {
if let Some(c) = self.chars.next() {
self.position += 1;
region.end += 1;
s.push(c);
}
}
@ -242,19 +189,16 @@ where
|| *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 +209,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,7 +221,7 @@ where
}
if let Some(token) = state.into_token() {
Some((region, Ok(token)))
Some(Ok(token))
} else {
None
}
@ -300,8 +244,8 @@ mod tests {
.chars(),
);
for (range, token) in lexer {
eprintln!("[{:?}] {:?}", range, token);
for token in lexer {
eprintln!("token = {:?}", token);
}
}
}

View file

@ -42,6 +42,24 @@ fn main() {
let main_scope = Scope::with_parent(&root_scope);
let typectx = main_scope.read().unwrap().typectx.clone();
/* define type of the symbol
*/
main_scope.write().unwrap().declare_static_parse(
"hello-string",
"<Seq Char
~Ascii
~machine::Word>
~<NullTerminatedSeq machine::Word>",
);
main_scope.write().unwrap().declare_static_parse(
"pfxstr",
"<Seq Char
~Ascii
~machine::Word>
~<LengthPrefixedSeq machine::Word>",
);
/* link assembly-program to symbols
*/
linker.add_procedure(
@ -50,79 +68,102 @@ fn main() {
&main_scope,
"main",
"{
let print-nullterm =
λ{} : < Seq Char~Ascii~machine::Word >
~ < NullTerminatedArray machine::Word >
{
while(dup) { emit; }
emit;
};
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);
}
};
print-nullterm 'H' 'a' 'l' 'l' 'o' ' ' 'W' 'e' 'l' 't' '!' '\n' '\0';
let print-uint =
λx : ~ _2^64 ~ machine::UInt64
{
if( x ) {
print-nullterm {
'\0';
while( x ) {
i+ '0' (i% x 10);
! x (i/ x 10);
}
};
} else {
emit '0';
};
};
let int-neg = λx : ~machine::Int64~machine::Word i+ (bit-neg x) 1;
let int-sign = λx : ~machine::Int64~machine::Word bit-and (bit-shr x 63) 1;
let int-lte = λ{
a : ~machine::Int64~machine::Word;
b : ~machine::Int64~machine::Word;
} int-sign (i- a b);
let int-max = λ{
a : ~machine::Int64~machine::Word;
b : ~machine::Int64~machine::Word;
} if( int-lte b a ) { a; } else { b; };
let vec3i-add = λ{
{ ax:_2^64; ay:_2^64; az:_2^64; } : <Vec3 _2^64~machine::UInt64>;
{ bx:_2^64; by:_2^64; bz:_2^64; } : <Vec3 _2^64~machine::UInt64>;
} {
i+ az bz;
i+ ay by;
i+ ax bx;
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-vec3i =
λ{ x:_2^64; y:_2^64; z:_2^64; } : <Vec3 _2^64~machine::UInt64>
{
print-nullterm '{' 'x' '=' '\0';
print-uint x;
print-nullterm ';' ' ' 'y' '=' '\0';
print-uint y;
print-nullterm ';' ' ' 'z' '=' '\0';
print-uint z;
print-nullterm '}' '\0';
};
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 len = (@ str);
! str (i+ str 1);
print-len len str;
};
let red-u8
: <Fn <> Color ~ RGB ~ <Vec3 _0,1 ~ _256 ~ machine::UInt64>>
= λ{} { 0; 0; 255; };
let green-u8 = λ{} { 0; 255; 0; };
let blue-u8 = λ{} { 255; 0; 0; };
let yellow-u8 = λ{} { 0; 220; 220; };
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 '!';
};
print-vec3i (vec3i-add green-u8 blue-u8);
emit '\n';
}"
emit (i+ '0' (isquare 3));
emit '\n';
};
hello;
}",
),
);
linker.add_static(
"hello-string",
"Hallo Welt!\n\0"
.chars()
.map(|c| (c as u8) as tisc::VM_Word)
.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,
],
);
let main_addr = linker
.get_link_addr(&"main".into())
.expect("'main' not linked");

View file

@ -9,13 +9,12 @@ use {
},
};
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug)]
pub enum ParseError {
LexError(LexError),
UnexpectedClose,
UnexpectedEnd,
UnexpectedToken,
TypeParseError(laddertypes::parser::ParseError)
}
pub fn parse_expect<It>(
@ -26,151 +25,53 @@ 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)),
Some(Err(err)) => Err(ParseError::LexError(err)),
None => Err(ParseError::UnexpectedEnd),
}
}
/* parse symbol name
*/
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),
}
}
/* parse an optional type annotation
* `: T`
*/
pub fn parse_type_tag<It>(
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
tokens: &mut Peekable<LTIRLexer<It>>,
) -> Result<Option<laddertypes::TypeTerm>, ParseError>
) -> Option<TypeTag>
where
It: Iterator<Item = char>,
{
if let Some((region, peektok)) = tokens.peek().clone() {
if let Some(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) => Ok(Some(typeterm)),
Err(parse_error) => Err(ParseError::TypeParseError(parse_error)),
Ok(typeterm) => Some(Ok(typeterm)),
Err(parse_error) => Some(Err(TypeError::ParseError(parse_error))),
}
}
_ => Ok(None),
_ => None,
}
} else {
Ok(None)
None
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum VariableBinding {
Atomic {
symbol: String,
typtag: Option<laddertypes::TypeTerm>
},
Struct {
members: Vec< VariableBinding >,
typtag: Option<laddertypes::TypeTerm>
}
}
impl VariableBinding {
pub fn flatten(self) -> Vec<(String, Option<laddertypes::TypeTerm>)> {
match self {
VariableBinding::Atomic{ symbol, typtag } =>
vec![ (symbol, typtag) ],
VariableBinding::Struct{ members, typtag } =>
members
.into_iter()
.map(|a| a.flatten().into_iter())
.flatten()
.collect()
}
}
}
/* parse a symbol binding of the form
* `x`
* or `x : T`
*/
pub fn parse_binding_expr<It>(
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
tokens: &mut Peekable<LTIRLexer<It>>,
) -> Result< VariableBinding, ParseError>
where It: Iterator<Item = char>
{
if let Some((region, peektok)) = tokens.peek().clone() {
match peektok {
Ok(LTIRToken::BlockOpen) => {
Ok(VariableBinding::Struct {
members: parse_binding_block(typectx, tokens)?,
typtag: parse_type_tag(typectx, tokens)?
})
}
Ok(LTIRToken::Symbol(_)) => {
Ok(VariableBinding::Atomic{
symbol: parse_symbol(tokens)?,
typtag: parse_type_tag(typectx, tokens)?
})
}
Err(err) => Err(ParseError::LexError(err.clone())),
_ => Err(ParseError::UnexpectedToken)
}
} else {
Err(ParseError::UnexpectedEnd)
}
}
/* parse a block of symbol bidnings
* `{ x:T; y:U; ... }`
*/
pub fn parse_binding_block<It>(
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
tokens: &mut Peekable<LTIRLexer<It>>,
) -> Result< Vec<VariableBinding>, ParseError>
where
It: Iterator<Item = char>,
{
let _ = parse_expect(tokens, LTIRToken::BlockOpen)?;
let mut bindings = Vec::new();
while let Some((region, peektok)) = tokens.peek() {
match peektok {
Ok(LTIRToken::BlockClose) => {
tokens.next();
return Ok(bindings);
}
Ok(LTIRToken::StatementSep) => {
tokens.next();
}
Ok(_) => {
bindings.push(parse_binding_expr(typectx, tokens)?);
}
Err(err) => {
return Err(ParseError::LexError(err.clone()));
}
}
}
Err(ParseError::UnexpectedEnd)
}
pub fn parse_statement<It>(
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
tokens: &mut Peekable<LTIRLexer<It>>,
@ -178,7 +79,7 @@ pub fn parse_statement<It>(
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() {
@ -197,19 +98,13 @@ where
"let" => {
tokens.next();
let name = parse_symbol(tokens)?;
let typ = parse_type_tag(typectx, tokens)?;
/* todo
let mut variable_bindings = parse_binding_expr(typectx, tokens)?;
*/
let typ = parse_type_tag(typectx, tokens);
let _ = parse_expect(tokens, LTIRToken::AssignValue);
let val_expr = parse_expr(typectx, tokens)?;
let _ = parse_expect(tokens, LTIRToken::StatementSep)?;
Ok(Statement::LetAssign {
typ: match typ {
Some(t) => Some(Ok(t)),
None => None
},
typ,
var_id: name,
val_expr,
})
@ -221,7 +116,7 @@ where
let _ = parse_expect(tokens, LTIRToken::ExprClose)?;
Ok(Statement::WhileLoop {
condition: cond,
body: parse_statement_block(typectx, tokens)?,
body: parse_block(typectx, tokens)?,
})
}
"return" => {
@ -249,7 +144,7 @@ where
}
}
pub fn parse_statement_block<It>(
pub fn parse_block<It>(
typectx: &Arc<RwLock<laddertypes::dict::TypeDict>>,
tokens: &mut Peekable<LTIRLexer<It>>,
) -> Result<Vec<Statement>, ParseError>
@ -259,7 +154,7 @@ where
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();
@ -284,11 +179,11 @@ 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)),
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),
}
}
@ -302,18 +197,22 @@ where
{
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 mut variable_bindings = parse_binding_expr(typectx, tokens)?;
let mut args = Vec::new();
while let Some(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: variable_bindings.flatten().into_iter().map(|(s,t)| (s,t.map(|t|Ok(t))) ).collect(),
args,
body: Box::new(body),
});
} else {
@ -322,7 +221,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();
@ -337,7 +236,7 @@ where
break;
}
Ok(LTIRToken::BlockOpen) => {
children.push(LTExpr::block(parse_statement_block(typectx, tokens)?));
children.push(LTExpr::block(parse_block(typectx, tokens)?));
}
Ok(LTIRToken::BlockClose) => {
break;
@ -351,10 +250,10 @@ where
let _ = parse_expect(tokens, LTIRToken::ExprOpen)?;
let cond = parse_expr(typectx, tokens)?;
let _ = parse_expect(tokens, LTIRToken::ExprClose)?;
let if_expr = LTExpr::block(parse_statement_block(typectx, tokens)?);
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 Some(peektok) = tokens.peek() {
if let Ok(LTIRToken::Symbol(name)) = peektok {
if name == "else" {
tokens.next();
@ -393,99 +292,3 @@ where
Err(ParseError::UnexpectedEnd)
}
}
mod tests {
use std::sync::{Arc, RwLock};
#[test]
fn test_parse_atomic_binding() {
let mut lexer = crate::lexer::LTIRLexer::from("x".chars()).peekable();
let typectx = Arc::new(RwLock::new(laddertypes::dict::TypeDict::new()));
let bindings = crate::parser::parse_binding_expr( &typectx, &mut lexer );
assert_eq!(
bindings,
Ok(crate::parser::VariableBinding::Atomic{
symbol: "x".into(),
typtag: None
})
);
}
#[test]
fn test_parse_typed_atomic_binding() {
let mut lexer = crate::lexer::LTIRLexer::from("x:T".chars()).peekable();
let typectx = Arc::new(RwLock::new(laddertypes::dict::TypeDict::new()));
let bindings = crate::parser::parse_binding_expr( &typectx, &mut lexer );
assert_eq!(
bindings,
Ok(crate::parser::VariableBinding::Atomic{
symbol: "x".into(),
typtag: Some(typectx.write().unwrap().parse("T").unwrap())
})
);
}
#[test]
fn test_parse_struct_binding() {
let mut lexer = crate::lexer::LTIRLexer::from("{x y}".chars()).peekable();
let typectx = Arc::new(RwLock::new(laddertypes::dict::TypeDict::new()));
let bindings = crate::parser::parse_binding_expr( &typectx, &mut lexer );
assert_eq!(
bindings,
Ok(crate::parser::VariableBinding::Struct{
members: vec![
crate::parser::VariableBinding::Atomic{ symbol: "x".into(), typtag: None },
crate::parser::VariableBinding::Atomic{ symbol: "y".into(), typtag: None }
],
typtag: None
})
);
}
#[test]
fn test_parse_typed_struct_binding1() {
let mut lexer = crate::lexer::LTIRLexer::from("{x y}:T".chars()).peekable();
let typectx = Arc::new(RwLock::new(laddertypes::dict::TypeDict::new()));
let bindings = crate::parser::parse_binding_expr( &typectx, &mut lexer );
assert_eq!(
bindings,
Ok(crate::parser::VariableBinding::Struct{
members: vec![
crate::parser::VariableBinding::Atomic{ symbol: "x".into(), typtag: None },
crate::parser::VariableBinding::Atomic{ symbol: "y".into(), typtag: None }
],
typtag: Some(typectx.write().unwrap().parse("T").unwrap())
})
);
}
#[test]
fn test_parse_typed_struct_binding2() {
let mut lexer = crate::lexer::LTIRLexer::from("{x:U; y}:T".chars()).peekable();
let typectx = Arc::new(RwLock::new(laddertypes::dict::TypeDict::new()));
let bindings = crate::parser::parse_binding_expr( &typectx, &mut lexer );
let type_u = typectx.write().unwrap().parse("U").unwrap();
let type_t = typectx.write().unwrap().parse("T").unwrap();
assert_eq!(
bindings,
Ok(crate::parser::VariableBinding::Struct{
members: vec![
crate::parser::VariableBinding::Atomic{
symbol: "x".into(),
typtag: Some(type_u)
},
crate::parser::VariableBinding::Atomic{ symbol: "y".into(), typtag: None }
],
typtag: Some(type_t)
})
);
}
}

View file

@ -18,14 +18,13 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
vec!["T~machine::Word", "T~machine::Word"],
);
/* drop topmost element
*/
symbols.write().unwrap().declare_proc_parse(
"drop",
vec!["T"],
vec!["T~machine::Word"],
vec![],
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(
@ -34,17 +33,13 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
vec!["Char~Ascii~machine::Word"],
vec![],
);
symbols.write().unwrap().declare_proc_parse(
"accept",
vec![],
vec![],
vec!["Char~Ascii~machine::Word"],
);
linker.add_procedure("dup", tisc::Assembler::new().inst(tisc::VM_Instruction::Dup).build());
linker.add_procedure("drop", tisc::Assembler::new().inst(tisc::VM_Instruction::Accept).build());
linker.add_procedure("emit", tisc::Assembler::new().inst(tisc::VM_Instruction::Emit).build());
linker.add_procedure("accept", tisc::Assembler::new().inst(tisc::VM_Instruction::Accept).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.
@ -60,43 +55,16 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
],
vec!["_2^64~machine::UInt64~machine::Word"],
);
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"],
);
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"],
);
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"],
);
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"],
linker.add_procedure(
"i+",
tisc::Assembler::new()
.inst(tisc::VM_Instruction::IntAdd)
.build(),
);
/* Floating-point Addition
*/
symbols.write().unwrap().declare_proc_parse(
"f+",
vec![],
@ -107,93 +75,35 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
vec!["~machine::f64~machine::Word"],
);
linker.add_procedure(
"f+",
tisc::Assembler::new()
.inst(tisc::VM_Instruction::FltAdd)
.build(),
);
/* Integer Subtraction
*/
symbols.write().unwrap().declare_proc_parse(
"f-",
"i-",
vec![],
vec![
"~machine::f64~machine::Word",
"~machine::f64~machine::Word",
"_2^64~machine::UInt64~machine::Word",
"_2^64~machine::UInt64~machine::Word",
],
vec!["~machine::f64~machine::Word"],
vec!["_2^64~machine::UInt64~machine::Word"],
);
symbols.write().unwrap().declare_proc_parse(
"f*",
vec![],
vec![
"~machine::f64~machine::Word",
"~machine::f64~machine::Word",
],
vec!["~machine::f64~machine::Word"],
linker.add_procedure(
"i-",
tisc::Assembler::new()
.inst(tisc::VM_Instruction::Swap)
.inst(tisc::VM_Instruction::BitNeg)
.lit(1)
.inst(tisc::VM_Instruction::IntAdd)
.inst(tisc::VM_Instruction::IntAdd)
.build(),
);
symbols.write().unwrap().declare_proc_parse(
"f/",
vec![],
vec![
"~machine::f64~machine::Word",
"~machine::f64~machine::Word",
],
vec!["~machine::f64~machine::Word"],
);
symbols.write().unwrap().declare_proc_parse(
"f%",
vec![],
vec![
"~machine::f64~machine::Word",
"~machine::f64~machine::Word",
],
vec!["~machine::f64~machine::Word"],
);
linker.add_procedure("i+", tisc::Assembler::new().inst(tisc::VM_Instruction::IntAdd).build());
linker.add_procedure("i-", tisc::Assembler::new().inst(tisc::VM_Instruction::IntSub).build());
linker.add_procedure("i*", tisc::Assembler::new().inst(tisc::VM_Instruction::IntMul).build());
linker.add_procedure("i/", tisc::Assembler::new().inst(tisc::VM_Instruction::IntDiv).build());
linker.add_procedure("i%", tisc::Assembler::new().inst(tisc::VM_Instruction::IntRem).build());
linker.add_procedure("f+", tisc::Assembler::new().inst(tisc::VM_Instruction::FltAdd).build());
linker.add_procedure("f-", tisc::Assembler::new().inst(tisc::VM_Instruction::FltSub).build());
linker.add_procedure("f*", tisc::Assembler::new().inst(tisc::VM_Instruction::FltMul).build());
linker.add_procedure("f/", tisc::Assembler::new().inst(tisc::VM_Instruction::FltDiv).build());
linker.add_procedure("f%", tisc::Assembler::new().inst(tisc::VM_Instruction::FltRem).build());
symbols.write().unwrap().declare_proc_parse(
"bit-neg",
vec![], vec!["machine::Word", "machine::Word"], vec!["machine::Word"],
);
symbols.write().unwrap().declare_proc_parse(
"bit-and",
vec![], vec!["machine::Word", "machine::Word"], vec!["machine::Word"],
);
symbols.write().unwrap().declare_proc_parse(
"bit-or",
vec![], vec!["machine::Word", "machine::Word"], vec!["machine::Word"],
);
symbols.write().unwrap().declare_proc_parse(
"bit-xor",
vec![], vec!["machine::Word", "machine::Word"], vec!["machine::Word"],
);
symbols.write().unwrap().declare_proc_parse(
"bit-shl",
vec![], vec!["machine::Word", "machine::Word"], vec!["machine::Word"],
);
symbols.write().unwrap().declare_proc_parse(
"bit-shr",
vec![], vec!["machine::Word", "machine::Word"], vec!["machine::Word"],
);
linker.add_procedure("bit-neg", tisc::Assembler::new().inst(tisc::VM_Instruction::BitNeg).build());
linker.add_procedure("bit-and", tisc::Assembler::new().inst(tisc::VM_Instruction::BitAnd).build());
linker.add_procedure("bit-or", tisc::Assembler::new().inst(tisc::VM_Instruction::BitOr).build());
linker.add_procedure("bit-xor", tisc::Assembler::new().inst(tisc::VM_Instruction::BitXor).build());
linker.add_procedure("bit-shl", tisc::Assembler::new().inst(tisc::VM_Instruction::BitShl).build());
linker.add_procedure("bit-shr", tisc::Assembler::new().inst(tisc::VM_Instruction::BitShr).build());
/* Fetch memory address
*/
symbols.write().unwrap().declare_proc_parse(
@ -202,6 +112,13 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
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(),
);
/* Store to memory
*/
symbols.write().unwrap().declare_proc_parse(
@ -213,11 +130,72 @@ pub fn init_runtime(linker: &mut Linker) -> Arc<RwLock<Scope>> {
],
vec![],
);
linker.add_procedure(
"!",
tisc::Assembler::new()
.inst(tisc::VM_Instruction::Store)
.build(),
);
linker.add_procedure("@", tisc::Assembler::new().inst(tisc::VM_Instruction::Fetch).build());
linker.add_procedure("!", tisc::Assembler::new().inst(tisc::VM_Instruction::Store).build());
/*
* let muli = λa.λb.{
* let mut sum = 0;
* while( b != 0 ) {
* sum := (addi sum a);
* b := (subi b 1);
* }
* sum
* };
*/
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"],
);
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),
// body
tisc::Assembler::new()
// [ a b sum ] -- [ a b sum a ]
.lit(3)
.inst(tisc::VM_Instruction::Pick)
// [ a b sum a -- a b (sum+a) ]
.inst(tisc::VM_Instruction::IntAdd)
// [ a b sum -- a sum b ]
.inst(tisc::VM_Instruction::Swap)
// [ a sum b -- a sum b 1 ]
.lit(1)
// [ a sum b -- a sum (b-1) ]
.inst(tisc::VM_Instruction::Swap)
.call("i-")
// [ a sum b -- a b sum ]
.inst(tisc::VM_Instruction::Swap),
)
// [ a b sum -- a sum b ]
.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)
// [ sum a -- sum ]
.inst(tisc::VM_Instruction::Drop)
.build(),
);
symbols.write().unwrap().declare_static_parse(
"data-frame-ptr",