Compare commits

..

No commits in common. "b8f040c6cef2781e4891e6c6ac97c57c48ce8df3" and "e4954678f018ee643b2bee5e4872db70db38f0dd" have entirely different histories.

4 changed files with 85 additions and 59 deletions

View File

@ -15,7 +15,7 @@ pub enum Token<'src> {
Punctuation(&'src str),
}
impl fmt::Display for Token<'_> {
impl<'src> fmt::Display for Token<'src> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Token::Number(n) => write!(f, "[Number {}]", n),
@ -60,7 +60,7 @@ pub fn lexer<'src>(
_ => Token::Word(word),
});
let keyword = just(':').ignore_then(word).map(Token::Keyword);
let keyword = just(':').ignore_then(word.clone()).map(Token::Keyword);
let string = just('"')
.ignore_then(none_of("\"").repeated().to_slice())

View File

@ -65,7 +65,7 @@ pub enum Ast<'src> {
Recur(Vec<Spanned<Self>>),
}
impl fmt::Display for Ast<'_> {
impl<'src> fmt::Display for Ast<'src> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Ast::Error => write!(f, "Error"),
@ -96,7 +96,7 @@ impl fmt::Display for Ast<'_> {
"#{{{}}}",
entries
.iter()
.map(|pair| pair.0.to_string())
.map(|pair| (*pair).0.to_string())
.collect::<Vec<_>>()
.join(", ")
),
@ -179,13 +179,13 @@ impl fmt::Display for Ast<'_> {
write!(f, "splat: {}", word)
}
Ast::Pair(k, v) => {
write!(f, "pair: {} {}", k, v.0)
write!(f, "pair: {} {}", k, (*v).0.to_string())
}
Ast::Loop(init, body) => {
write!(
f,
"loop: {} with {}",
init.0,
(*init).0.to_string(),
body.iter()
.map(|clause| clause.to_string())
.collect::<Vec<_>>()
@ -235,7 +235,7 @@ pub enum Pattern<'src> {
Dict(Vec<Spanned<Self>>),
}
impl fmt::Display for Pattern<'_> {
impl<'src> fmt::Display for Pattern<'src> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Pattern::Nil => write!(f, "nil"),
@ -245,7 +245,7 @@ impl fmt::Display for Pattern<'_> {
Pattern::Keyword(k) => write!(f, ":{}", k),
Pattern::Word(w) => write!(f, "{}", w),
Pattern::As(w, t) => write!(f, "{} as {}", w, t),
Pattern::Splattern(p) => write!(f, "...{}", p.0),
Pattern::Splattern(p) => write!(f, "...{}", (*p).0.to_string()),
Pattern::Placeholder => write!(f, "_"),
Pattern::Tuple(t) => write!(
f,
@ -325,7 +325,7 @@ where
)
});
let splattable = word_pattern.or(placeholder_pattern);
let splattable = word_pattern.clone().or(placeholder_pattern.clone());
let patt_splat = just(Token::Punctuation("..."))
.ignore_then(splattable)
@ -430,9 +430,9 @@ where
.delimited_by(just(Token::Punctuation("(")), just(Token::Punctuation(")")))
.map_with(|args, e| (Ast::Arguments(args), e.span()));
let synth_root = word.or(keyword);
let synth_root = word.clone().or(keyword.clone());
let synth_term = keyword.or(args);
let synth_term = keyword.clone().or(args);
let synthetic = synth_root
.then(synth_term.clone())
@ -445,7 +445,7 @@ where
});
let splat = just(Token::Punctuation("..."))
.ignore_then(word)
.ignore_then(word.clone())
.map_with(|(w, _), e| {
(
Ast::Splat(if let Ast::Word(w) = w {
@ -693,7 +693,7 @@ where
});
let box_ = just(Token::Reserved("box"))
.ignore_then(word)
.ignore_then(word.clone())
.then_ignore(just(Token::Punctuation("=")))
.then(nonbinding.clone())
.map_with(|(word, expr), e| {
@ -706,7 +706,7 @@ where
});
let fn_decl = just(Token::Reserved("fn"))
.ignore_then(word)
.ignore_then(word.clone())
.map_with(|(word, _), e| {
let name = if let Ast::Word(w) = word {
w
@ -717,7 +717,7 @@ where
});
let fn_named = just(Token::Reserved("fn"))
.ignore_then(word)
.ignore_then(word.clone())
.then(fn_unguarded.clone())
.map_with(|(word, clause), e| {
let name = if let Ast::Word(word) = word.0 {
@ -729,7 +729,7 @@ where
});
let fn_compound = just(Token::Reserved("fn"))
.ignore_then(word)
.ignore_then(word.clone())
.then(fn_multiclause.clone())
.map_with(|(word, clauses), e| {
let name = if let Ast::Word(word) = word.0 {

View File

@ -48,10 +48,10 @@ impl<'src> Clone for Value<'src> {
fn clone(&self) -> Value<'src> {
match self {
Value::Nil => Value::Nil,
Value::Boolean(b) => Value::Boolean(*b),
Value::Boolean(b) => Value::Boolean(b.clone()),
Value::String(s) => Value::String(s),
Value::Keyword(s) => Value::Keyword(s),
Value::Number(n) => Value::Number(*n),
Value::Number(n) => Value::Number(n.clone()),
Value::Tuple(t) => Value::Tuple(t.clone()),
Value::Args(a) => Value::Args(a.clone()),
Value::Fn(f) => Value::Fn(f.clone()),
@ -65,7 +65,7 @@ impl<'src> Clone for Value<'src> {
}
}
impl fmt::Display for Value<'_> {
impl<'src> fmt::Display for Value<'src> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Value::Nil => write!(f, "nil"),
@ -120,9 +120,12 @@ impl fmt::Display for Value<'_> {
}
}
impl Value<'_> {
impl<'src> Value<'src> {
pub fn bool(&self) -> bool {
matches!(self, Value::Nil | Value::Boolean(false))
match self {
Value::Nil | Value::Boolean(false) => false,
_ => true,
}
}
pub fn ludus_type(&self) -> Value {
@ -167,4 +170,4 @@ impl<'src> PartialEq for Value<'src> {
}
}
impl Eq for Value<'_> {}
impl<'src> Eq for Value<'src> {}

View File

@ -79,9 +79,13 @@ pub fn match_pattern<'src, 'a>(
}
// todo: add splats to these match clauses
(Pattern::Tuple(x), Value::Tuple(y)) => {
let has_splat = x
.iter()
.any(|patt| matches!(patt, (Pattern::Splattern(_), _)));
let has_splat = x.iter().any(|patt| {
if let (Pattern::Splattern(_), _) = patt {
true
} else {
false
}
});
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
@ -93,58 +97,71 @@ pub fn match_pattern<'src, 'a>(
list.push_back(y[i].clone())
}
let list = Value::List(list);
match_pattern(&patt.0, &list, ctx);
} else if match_pattern(&x[i].0, &y[i], ctx).is_none() {
match_pattern(&(*patt).0, &list, ctx);
} else {
if let None = match_pattern(&x[i].0, &y[i], ctx) {
while ctx.len() > to {
ctx.pop();
}
return None;
}
}
}
Some(ctx)
}
(Pattern::List(x), Value::List(y)) => {
let has_splat = x
.iter()
.any(|patt| matches!(patt, (Pattern::Splattern(_), _)));
let has_splat = x.iter().any(|patt| {
if let (Pattern::Splattern(_), _) = patt {
true
} else {
false
}
});
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
let to = ctx.len();
for (i, (patt, _)) in x.iter().enumerate() {
if let Pattern::Splattern(patt) = &patt {
for i in 0..x.len() {
if let Pattern::Splattern(patt) = &x[i].0 {
let list = Value::List(y.skip(i));
match_pattern(&patt.0, &list, ctx);
} else if match_pattern(patt, y.get(i).unwrap(), ctx).is_none() {
match_pattern(&(*patt).0, &list, ctx);
} else {
if let None = match_pattern(&x[i].0, &y.get(i).unwrap(), ctx) {
while ctx.len() > to {
ctx.pop();
}
return None;
}
}
}
Some(ctx)
}
// TODO: optimize this on several levels
// - [ ] opportunistic mutation
// - [ ] get rid of all the pointer indirection in word splats
(Pattern::Dict(x), Value::Dict(y)) => {
let has_splat = x
.iter()
.any(|patt| matches!(patt, (Pattern::Splattern(_), _)));
let has_splat = x.iter().any(|patt| {
if let (Pattern::Splattern(_), _) = patt {
true
} else {
false
}
});
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
let to = ctx.len();
let mut matched = vec![];
for (pattern, _) in x {
for i in 0..x.len() {
let (pattern, _) = &x[i];
match pattern {
Pattern::Pair(key, patt) => {
if let Some(val) = y.get(key) {
if match_pattern(&patt.0, val, ctx).is_none() {
if let None = match_pattern(&patt.0, val, ctx) {
while ctx.len() > to {
ctx.pop();
}
return None;
}
} else {
matched.push(key);
}
@ -152,7 +169,7 @@ pub fn match_pattern<'src, 'a>(
return None;
};
}
Pattern::Splattern(pattern) => match pattern.0 {
Pattern::Splattern(pattern) => match &(*pattern).0 {
Pattern::Word(w) => {
// TODO: find a way to take ownership
// this will ALWAYS make structural changes, because of this clone
@ -161,7 +178,7 @@ pub fn match_pattern<'src, 'a>(
for key in matched.iter() {
unmatched.remove(*key);
}
ctx.push((w, Value::Dict(unmatched)));
ctx.push((*w, Value::Dict(unmatched)));
}
Pattern::Placeholder => (),
_ => unreachable!(),
@ -175,10 +192,10 @@ pub fn match_pattern<'src, 'a>(
}
}
pub fn match_clauses<'src>(
pub fn match_clauses<'src, 'a>(
value: &Value<'src>,
clauses: &'src Vec<MatchClause<'src>>,
ctx: &mut Vec<(&'src str, Value<'src>)>,
ctx: &'a mut Vec<(&'src str, Value<'src>)>,
) -> Result<Value<'src>, LudusError> {
let to = ctx.len();
for MatchClause { patt, body, guard } in clauses.iter() {
@ -186,7 +203,7 @@ pub fn match_clauses<'src>(
let pass_guard = match guard {
None => true,
Some((ast, _)) => {
let guard_res = eval(ast, ctx);
let guard_res = eval(&ast, ctx);
match &guard_res {
Err(_) => return guard_res,
Ok(val) => val.bool(),
@ -211,10 +228,10 @@ pub fn match_clauses<'src>(
})
}
pub fn apply<'src>(
pub fn apply<'src, 'a>(
callee: Value<'src>,
caller: Value<'src>,
ctx: &mut Vec<(&'src str, Value<'src>)>,
ctx: &'a mut Vec<(&'src str, Value<'src>)>,
) -> Result<Value<'src>, LudusError> {
match (callee, caller) {
(Value::Keyword(kw), Value::Dict(dict)) => {
@ -351,10 +368,16 @@ pub fn eval<'src, 'a>(
Ast::Arguments(a) => {
let mut args = vec![];
for (arg, _) in a.iter() {
let arg = eval(arg, ctx)?;
let arg = eval(&arg, ctx)?;
args.push(arg);
}
if args.iter().any(|arg| matches!(arg, Value::Placeholder)) {
if args.iter().any(|arg| {
if let Value::Placeholder = arg {
true
} else {
false
}
}) {
Ok(Value::Args(Rc::new(args)))
} else {
Ok(Value::Tuple(Rc::new(args)))
@ -406,9 +429,9 @@ pub fn eval<'src, 'a>(
return eval(&body.0, ctx);
};
}
Err(LudusError {
return Err(LudusError {
msg: "no match".to_string(),
})
});
}
Ast::Match(value, clauses) => {
let value = eval(&value.0, ctx)?;
@ -445,8 +468,8 @@ pub fn eval<'src, 'a>(
}
Ast::Do(terms) => {
let mut result = eval(&terms[0].0, ctx)?;
for (term, _) in terms.iter().skip(1) {
let next = eval(term, ctx)?;
for i in 1..terms.len() {
let next = eval(&terms[i].0, ctx)?;
let arg = Value::Tuple(Rc::new(vec![result]));
result = apply(next, arg, ctx)?;
}