Variables in pattern match
This commit is contained in:
parent
9e799c23ba
commit
df173a0096
@ -8,7 +8,7 @@ mod visitor;
|
|||||||
mod operators;
|
mod operators;
|
||||||
|
|
||||||
pub use operators::{PrefixOp, BinOp};
|
pub use operators::{PrefixOp, BinOp};
|
||||||
pub use visitor::{walk_ast, walk_block, ASTVisitor, Recursion};
|
pub use visitor::*;
|
||||||
|
|
||||||
use crate::derivative::Derivative;
|
use crate::derivative::Derivative;
|
||||||
use crate::tokenizing::Location;
|
use crate::tokenizing::Location;
|
||||||
|
@ -42,7 +42,7 @@ pub fn walk_block<V: ASTVisitor>(v: &mut V, block: &Block) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn walk_declaration<V: ASTVisitor>(v: &mut V, decl: &Declaration, id: &ItemId) {
|
pub fn walk_declaration<V: ASTVisitor>(v: &mut V, decl: &Declaration, id: &ItemId) {
|
||||||
use Declaration::*;
|
use Declaration::*;
|
||||||
|
|
||||||
if let Recursion::Continue = v.declaration(decl, id) {
|
if let Recursion::Continue = v.declaration(decl, id) {
|
||||||
@ -63,7 +63,7 @@ fn walk_declaration<V: ASTVisitor>(v: &mut V, decl: &Declaration, id: &ItemId) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn walk_expression<V: ASTVisitor>(v: &mut V, expr: &Expression) {
|
pub fn walk_expression<V: ASTVisitor>(v: &mut V, expr: &Expression) {
|
||||||
use ExpressionKind::*;
|
use ExpressionKind::*;
|
||||||
|
|
||||||
if let Recursion::Continue = v.expression(expr) {
|
if let Recursion::Continue = v.expression(expr) {
|
||||||
@ -142,7 +142,7 @@ fn walk_expression<V: ASTVisitor>(v: &mut V, expr: &Expression) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn walk_if_expr_body<V: ASTVisitor>(v: &mut V, body: &IfExpressionBody) {
|
pub fn walk_if_expr_body<V: ASTVisitor>(v: &mut V, body: &IfExpressionBody) {
|
||||||
use IfExpressionBody::*;
|
use IfExpressionBody::*;
|
||||||
|
|
||||||
match body {
|
match body {
|
||||||
@ -189,7 +189,7 @@ fn walk_if_expr_body<V: ASTVisitor>(v: &mut V, body: &IfExpressionBody) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn walk_pattern<V: ASTVisitor>(v: &mut V, pat: &Pattern) {
|
pub fn walk_pattern<V: ASTVisitor>(v: &mut V, pat: &Pattern) {
|
||||||
use Pattern::*;
|
use Pattern::*;
|
||||||
|
|
||||||
if let Recursion::Continue = v.pattern(pat) {
|
if let Recursion::Continue = v.pattern(pat) {
|
||||||
|
@ -332,11 +332,9 @@ impl ast::Pattern {
|
|||||||
ast::Pattern::TupleStruct(name, subpatterns) => {
|
ast::Pattern::TupleStruct(name, subpatterns) => {
|
||||||
let symbol = symbol_table.lookup_symbol(&name.id).unwrap();
|
let symbol = symbol_table.lookup_symbol(&name.id).unwrap();
|
||||||
if let SymbolSpec::DataConstructor { index: tag, type_id, arity } = symbol.spec() {
|
if let SymbolSpec::DataConstructor { index: tag, type_id, arity } = symbol.spec() {
|
||||||
|
|
||||||
let items: Vec<_> = subpatterns.iter().map(|pat| pat.reduce(symbol_table)).collect();
|
let items: Vec<_> = subpatterns.iter().map(|pat| pat.reduce(symbol_table)).collect();
|
||||||
let items: Result<Vec<Pattern>, PatternError> = items.into_iter().collect();
|
let items: Result<Vec<Pattern>, PatternError> = items.into_iter().collect();
|
||||||
let items = items?;
|
let items = items?;
|
||||||
|
|
||||||
Pattern::Tuple {
|
Pattern::Tuple {
|
||||||
tag: Some(tag as u32),
|
tag: Some(tag as u32),
|
||||||
subpatterns: items,
|
subpatterns: items,
|
||||||
@ -349,7 +347,8 @@ impl ast::Pattern {
|
|||||||
//TODO fix this symbol not existing
|
//TODO fix this symbol not existing
|
||||||
let symbol = symbol_table.lookup_symbol(&name.id).unwrap();
|
let symbol = symbol_table.lookup_symbol(&name.id).unwrap();
|
||||||
println!("VarOrName symbol: {:?}", symbol);
|
println!("VarOrName symbol: {:?}", symbol);
|
||||||
Pattern::Ignored
|
let def_id = symbol.def_id().unwrap().clone();
|
||||||
|
Pattern::Binding(def_id)
|
||||||
},
|
},
|
||||||
ast::Pattern::Record(name, /*Vec<(Rc<String>, Pattern)>*/ _) => {
|
ast::Pattern::Record(name, /*Vec<(Rc<String>, Pattern)>*/ _) => {
|
||||||
unimplemented!()
|
unimplemented!()
|
||||||
|
@ -131,6 +131,7 @@ pub enum Pattern {
|
|||||||
},
|
},
|
||||||
Literal(Literal),
|
Literal(Literal),
|
||||||
Ignored,
|
Ignored,
|
||||||
|
Binding(DefId)
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
@ -221,6 +221,15 @@ impl SymbolTable {
|
|||||||
self.id_to_symbol.iter().find(|(_, sym)| sym.def_id == *def)
|
self.id_to_symbol.iter().find(|(_, sym)| sym.def_id == *def)
|
||||||
.map(|(_, sym)| sym.as_ref())
|
.map(|(_, sym)| sym.as_ref())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn debug(&self) {
|
||||||
|
println!("Symbol table:");
|
||||||
|
println!("----------------");
|
||||||
|
for (id, sym) in self.id_to_symbol.iter() {
|
||||||
|
println!("{} => {}", id, sym);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
@ -247,7 +256,7 @@ impl Symbol {
|
|||||||
|
|
||||||
impl fmt::Display for Symbol {
|
impl fmt::Display for Symbol {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
write!(f, "<Local name: {}, Spec: {}>", self.local_name(), self.spec)
|
write!(f, "<Local name: {}, {}, Spec: {}>", self.local_name(), self.fully_qualified_name, self.spec)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -322,6 +331,7 @@ impl SymbolTable {
|
|||||||
spec,
|
spec,
|
||||||
def_id,
|
def_id,
|
||||||
});
|
});
|
||||||
|
println!("In add_symbol(), adding: {:?}", symbol);
|
||||||
self.symbol_trie.insert(&fqsn);
|
self.symbol_trie.insert(&fqsn);
|
||||||
self.fqsn_to_symbol.insert(fqsn, symbol.clone());
|
self.fqsn_to_symbol.insert(fqsn, symbol.clone());
|
||||||
self.id_to_symbol.insert(id.clone(), symbol.clone());
|
self.id_to_symbol.insert(id.clone(), symbol.clone());
|
||||||
|
@ -18,11 +18,14 @@ enum ScopeType {
|
|||||||
name: Rc<String>
|
name: Rc<String>
|
||||||
},
|
},
|
||||||
Lambda,
|
Lambda,
|
||||||
|
PatternMatch,
|
||||||
//TODO add some notion of a let-like scope?
|
//TODO add some notion of a let-like scope?
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ScopeResolver<'a> {
|
pub struct ScopeResolver<'a> {
|
||||||
symbol_table: &'a mut super::SymbolTable,
|
symbol_table: &'a mut super::SymbolTable,
|
||||||
|
//TODO maybe this shouldn't be a scope stack, b/c the recursion behavior comes from multiple
|
||||||
|
//instances of ScopeResolver
|
||||||
lexical_scopes: ScopeStack<'a, Rc<String>, NameType, ScopeType>,
|
lexical_scopes: ScopeStack<'a, Rc<String>, NameType, ScopeType>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -225,6 +228,61 @@ impl<'a> ASTVisitor for ScopeResolver<'a> {
|
|||||||
walk_block(&mut new_resolver, body);
|
walk_block(&mut new_resolver, body);
|
||||||
return Recursion::Stop;
|
return Recursion::Stop;
|
||||||
}
|
}
|
||||||
|
IfExpression { discriminator, body } => {
|
||||||
|
if let Some(d) = discriminator.as_ref() {
|
||||||
|
walk_expression(self, &d);
|
||||||
|
}
|
||||||
|
let mut resolver = ScopeResolver {
|
||||||
|
lexical_scopes: self.lexical_scopes.new_scope(Some(ScopeType::PatternMatch)),
|
||||||
|
symbol_table: self.symbol_table
|
||||||
|
};
|
||||||
|
let new_resolver = &mut resolver;
|
||||||
|
|
||||||
|
match body.as_ref() {
|
||||||
|
IfExpressionBody::SimpleConditional {
|
||||||
|
then_case,
|
||||||
|
else_case,
|
||||||
|
} => {
|
||||||
|
walk_block(new_resolver, then_case);
|
||||||
|
if let Some(block) = else_case.as_ref() {
|
||||||
|
walk_block(new_resolver, block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
IfExpressionBody::SimplePatternMatch {
|
||||||
|
pattern,
|
||||||
|
then_case,
|
||||||
|
else_case,
|
||||||
|
} => {
|
||||||
|
walk_pattern(new_resolver, pattern);
|
||||||
|
walk_block(new_resolver, &then_case);
|
||||||
|
if let Some(ref block) = else_case.as_ref() {
|
||||||
|
walk_block(new_resolver, &block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
IfExpressionBody::CondList(arms) => {
|
||||||
|
for arm in arms {
|
||||||
|
match arm.condition {
|
||||||
|
Condition::Pattern(ref pat) => {
|
||||||
|
walk_pattern(new_resolver, pat);
|
||||||
|
}
|
||||||
|
Condition::TruncatedOp(ref _binop, ref expr) => {
|
||||||
|
walk_expression(new_resolver, expr);
|
||||||
|
}
|
||||||
|
Condition::Expression(ref expr) => {
|
||||||
|
walk_expression(new_resolver, expr);
|
||||||
|
}
|
||||||
|
Condition::Else => (),
|
||||||
|
}
|
||||||
|
if let Some(ref guard) = arm.guard {
|
||||||
|
walk_expression(new_resolver, &guard);
|
||||||
|
}
|
||||||
|
walk_block(new_resolver, &arm.body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return Recursion::Stop;
|
||||||
|
},
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
Recursion::Continue
|
Recursion::Continue
|
||||||
@ -234,12 +292,20 @@ impl<'a> ASTVisitor for ScopeResolver<'a> {
|
|||||||
use Pattern::*;
|
use Pattern::*;
|
||||||
|
|
||||||
match pat {
|
match pat {
|
||||||
//TODO I think not handling TuplePattern is an oversight
|
Literal(..) | Ignored | TuplePattern(..) => (),
|
||||||
TuplePattern(_) => (),
|
TupleStruct(name, _) | Record(name, _) => {
|
||||||
Literal(_) | Ignored => (),
|
|
||||||
TupleStruct(name, _) | Record(name, _) | VarOrName(name) => {
|
|
||||||
self.lookup_name_in_scope(name);
|
self.lookup_name_in_scope(name);
|
||||||
}
|
}
|
||||||
|
//TODO this isn't really the right syntax for a VarOrName
|
||||||
|
VarOrName(ref name @ QualifiedName { id, components }) => {
|
||||||
|
//TODO need a better way to construct a FQSN from a QualifiedName
|
||||||
|
let local_name: Rc<String> = components[0].clone();
|
||||||
|
let lscope = Scope::Name(Rc::new("<local-case-match>".to_string()));
|
||||||
|
let fqsn = Fqsn { scopes: vec![lscope, Scope::Name(local_name.clone())] };
|
||||||
|
//let local_name = fqsn.local_name();
|
||||||
|
self.symbol_table.add_symbol(id, fqsn, SymbolSpec::LocalVariable);
|
||||||
|
self.lexical_scopes.insert(local_name.clone(), NameType::LocalVariable(id.clone()));
|
||||||
|
},
|
||||||
};
|
};
|
||||||
Recursion::Continue
|
Recursion::Continue
|
||||||
}
|
}
|
||||||
|
@ -276,9 +276,14 @@ impl<'a> State<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn case_match_expression(&mut self, cond: Expression, alternatives: Vec<Alternative>) -> EvalResult<Primitive> {
|
fn case_match_expression(&mut self, cond: Expression, alternatives: Vec<Alternative>) -> EvalResult<Primitive> {
|
||||||
fn matches(scrut: &Primitive, pat: &Pattern) -> bool {
|
fn matches(scrut: &Primitive, pat: &Pattern, scope: &mut ScopeStack<Memory, MemoryValue>) -> bool {
|
||||||
match pat {
|
match pat {
|
||||||
Pattern::Ignored => true,
|
Pattern::Ignored => true,
|
||||||
|
Pattern::Binding(ref def_id) => {
|
||||||
|
let mem = def_id.into();
|
||||||
|
scope.insert(mem, MemoryValue::Primitive(scrut.clone())); //TODO make sure this doesn't cause problems with nesting
|
||||||
|
true
|
||||||
|
},
|
||||||
Pattern::Literal(pat_literal) => if let Primitive::Literal(scrut_literal) = scrut {
|
Pattern::Literal(pat_literal) => if let Primitive::Literal(scrut_literal) = scrut {
|
||||||
pat_literal == scrut_literal
|
pat_literal == scrut_literal
|
||||||
} else {
|
} else {
|
||||||
@ -287,13 +292,13 @@ impl<'a> State<'a> {
|
|||||||
Pattern::Tuple { subpatterns, tag } => match tag {
|
Pattern::Tuple { subpatterns, tag } => match tag {
|
||||||
None => match scrut {
|
None => match scrut {
|
||||||
Primitive::Tuple(items) if items.len() == subpatterns.len() =>
|
Primitive::Tuple(items) if items.len() == subpatterns.len() =>
|
||||||
items.iter().zip(subpatterns.iter()).all(|(item, subpat)| matches(item, subpat)),
|
items.iter().zip(subpatterns.iter()).all(|(item, subpat)| matches(item, subpat, scope)),
|
||||||
_ => false //TODO should be a type error
|
_ => false //TODO should be a type error
|
||||||
},
|
},
|
||||||
Some(pattern_tag) => match scrut {
|
Some(pattern_tag) => match scrut {
|
||||||
//TODO should test type_ids for runtime type checking, once those work
|
//TODO should test type_ids for runtime type checking, once those work
|
||||||
Primitive::Object { tag, items, .. } if tag == pattern_tag && items.len() == subpatterns.len() => {
|
Primitive::Object { tag, items, .. } if tag == pattern_tag && items.len() == subpatterns.len() => {
|
||||||
items.iter().zip(subpatterns.iter()).all(|(item, subpat)| matches(item, subpat))
|
items.iter().zip(subpatterns.iter()).all(|(item, subpat)| matches(item, subpat, scope))
|
||||||
}
|
}
|
||||||
_ => false
|
_ => false
|
||||||
}
|
}
|
||||||
@ -303,9 +308,13 @@ impl<'a> State<'a> {
|
|||||||
let cond = self.expression(cond)?;
|
let cond = self.expression(cond)?;
|
||||||
|
|
||||||
for alt in alternatives.into_iter() {
|
for alt in alternatives.into_iter() {
|
||||||
if matches(&cond, &alt.pattern) {
|
let mut new_scope = self.environments.new_scope(None);
|
||||||
// Set up local vars
|
if matches(&cond, &alt.pattern, &mut new_scope) {
|
||||||
return self.block(alt.item)
|
let mut new_state = State {
|
||||||
|
environments: new_scope
|
||||||
|
};
|
||||||
|
|
||||||
|
return new_state.block(alt.item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err("No valid match in match expression".into())
|
Err("No valid match in match expression".into())
|
||||||
@ -382,7 +391,11 @@ impl<'a> State<'a> {
|
|||||||
},
|
},
|
||||||
/* Binops */
|
/* Binops */
|
||||||
(binop, &[ref lhs, ref rhs]) => match (binop, lhs, rhs) {
|
(binop, &[ref lhs, ref rhs]) => match (binop, lhs, rhs) {
|
||||||
|
// TODO need a better way of handling these literals
|
||||||
(Add, Lit(Nat(l)), Lit(Nat(r))) => Nat(l + r).into(),
|
(Add, Lit(Nat(l)), Lit(Nat(r))) => Nat(l + r).into(),
|
||||||
|
(Add, Lit(Int(l)), Lit(Int(r))) => Int(l + r).into(),
|
||||||
|
(Add, Lit(Nat(l)), Lit(Int(r))) => Int((*l as i64) + (*r as i64)).into(),
|
||||||
|
(Add, Lit(Int(l)), Lit(Nat(r))) => Int((*l as i64) + (*r as i64)).into(),
|
||||||
(Concatenate, Lit(StringLit(ref s1)), Lit(StringLit(ref s2))) => StringLit(Rc::new(format!("{}{}", s1, s2))).into(),
|
(Concatenate, Lit(StringLit(ref s1)), Lit(StringLit(ref s2))) => StringLit(Rc::new(format!("{}{}", s1, s2))).into(),
|
||||||
(Subtract, Lit(Nat(l)), Lit(Nat(r))) => Nat(l - r).into(),
|
(Subtract, Lit(Nat(l)), Lit(Nat(r))) => Nat(l - r).into(),
|
||||||
(Multiply, Lit(Nat(l)), Lit(Nat(r))) => Nat(l * r).into(),
|
(Multiply, Lit(Nat(l)), Lit(Nat(r))) => Nat(l * r).into(),
|
||||||
|
@ -10,6 +10,8 @@ fn evaluate_input(input: &str) -> Result<String, String> {
|
|||||||
symbol_table.process_ast(&ast).unwrap();
|
symbol_table.process_ast(&ast).unwrap();
|
||||||
let reduced_ir = crate::reduced_ir::reduce(&ast, &symbol_table);
|
let reduced_ir = crate::reduced_ir::reduce(&ast, &symbol_table);
|
||||||
reduced_ir.debug(&symbol_table);
|
reduced_ir.debug(&symbol_table);
|
||||||
|
println!("========");
|
||||||
|
symbol_table.debug();
|
||||||
let mut state = State::new();
|
let mut state = State::new();
|
||||||
let mut outputs = state.evaluate(reduced_ir, true);
|
let mut outputs = state.evaluate(reduced_ir, true);
|
||||||
outputs.pop().unwrap()
|
outputs.pop().unwrap()
|
||||||
@ -134,16 +136,17 @@ println!("{}", source);
|
|||||||
fn if_is_patterns() {
|
fn if_is_patterns() {
|
||||||
let source = r#"
|
let source = r#"
|
||||||
type Option<T> = Some(T) | None
|
type Option<T> = Some(T) | None
|
||||||
|
let q = "a string"
|
||||||
let x = Option::Some(9); if x is Option::Some(q) then { q } else { 0 }"#;
|
let x = Option::Some(9); if x is Option::Some(q) then { q } else { 0 }"#;
|
||||||
|
|
||||||
eval_assert(source, "9");
|
eval_assert(source, "9");
|
||||||
|
|
||||||
/*
|
|
||||||
let source = r#"
|
let source = r#"
|
||||||
type Option<T> = Some(T) | None
|
type Option<T> = Some(T) | None
|
||||||
let x = Option::None; if x is Option::Some(q) then { q } else { 0 }"#;
|
let q = "a string"
|
||||||
|
let outer = 2
|
||||||
|
let x = Option::None; if x is Option::Some(q) then { q } else { -2 + outer }"#;
|
||||||
eval_assert(source, "0");
|
eval_assert(source, "0");
|
||||||
*/
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user