Enum cranelift_isle::sema::Pattern
source · pub enum Pattern {
BindPattern(TypeId, VarId, Box<Pattern>),
Var(TypeId, VarId),
ConstInt(TypeId, i128),
ConstPrim(TypeId, Sym),
Term(TypeId, TermId, Vec<Pattern>),
Wildcard(TypeId),
And(TypeId, Vec<Pattern>),
}
Expand description
A left-hand side pattern of some rule.
Variants§
BindPattern(TypeId, VarId, Box<Pattern>)
Bind a variable of the given type from the current value.
Keep matching on the value with the subpattern.
Var(TypeId, VarId)
Match the current value against an already bound variable with the given type.
ConstInt(TypeId, i128)
Match the current value against a constant integer of the given integer type.
ConstPrim(TypeId, Sym)
Match the current value against a constant primitive value of the given primitive type.
Term(TypeId, TermId, Vec<Pattern>)
Match the current value against the given extractor term with the given arguments.
Wildcard(TypeId)
Match anything of the given type successfully.
And(TypeId, Vec<Pattern>)
Match all of the following patterns of the given type.
Implementations§
source§impl Pattern
impl Pattern
sourcepub fn ty(&self) -> TypeId
pub fn ty(&self) -> TypeId
Get this pattern’s type.
Examples found in repository?
src/sema.rs (line 633)
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
pub fn visit<V: PatternVisitor>(
&self,
visitor: &mut V,
input: V::PatternId,
termenv: &TermEnv,
vars: &mut HashMap<VarId, V::PatternId>,
) {
match self {
&Pattern::BindPattern(_ty, var, ref subpat) => {
// Bind the appropriate variable and recurse.
assert!(!vars.contains_key(&var));
vars.insert(var, input);
subpat.visit(visitor, input, termenv, vars);
}
&Pattern::Var(ty, var) => {
// Assert that the value matches the existing bound var.
let var_val = vars
.get(&var)
.copied()
.expect("Variable should already be bound");
visitor.add_match_equal(input, var_val, ty);
}
&Pattern::ConstInt(ty, value) => visitor.add_match_int(input, ty, value),
&Pattern::ConstPrim(ty, value) => visitor.add_match_prim(input, ty, value),
&Pattern::Term(ty, term, ref args) => {
// Determine whether the term has an external extractor or not.
let termdata = &termenv.terms[term.index()];
let arg_values = match &termdata.kind {
TermKind::EnumVariant { variant } => {
visitor.add_match_variant(input, ty, &termdata.arg_tys, *variant)
}
TermKind::Decl {
extractor_kind: None,
..
} => {
panic!("Pattern invocation of undefined term body")
}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { .. }),
..
} => {
panic!("Should have been expanded away")
}
TermKind::Decl {
multi,
extractor_kind: Some(ExtractorKind::ExternalExtractor { infallible, .. }),
..
} => {
// Evaluate all `input` args.
let output_tys = args.iter().map(|arg| arg.ty()).collect();
// Invoke the extractor.
visitor.add_extract(
input,
termdata.ret_ty,
output_tys,
term,
*infallible && !*multi,
*multi,
)
}
};
for (pat, val) in args.iter().zip(arg_values) {
pat.visit(visitor, val, termenv, vars);
}
}
&Pattern::And(_ty, ref children) => {
for child in children {
child.visit(visitor, input, termenv, vars);
}
}
&Pattern::Wildcard(_ty) => {
// Nothing!
}
}
}
sourcepub fn visit<V: PatternVisitor>(
&self,
visitor: &mut V,
input: V::PatternId,
termenv: &TermEnv,
vars: &mut HashMap<VarId, V::PatternId>
)
pub fn visit<V: PatternVisitor>(
&self,
visitor: &mut V,
input: V::PatternId,
termenv: &TermEnv,
vars: &mut HashMap<VarId, V::PatternId>
)
Recursively visit every sub-pattern.
Examples found in repository?
src/sema.rs (line 596)
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
pub fn visit<V: PatternVisitor>(
&self,
visitor: &mut V,
input: V::PatternId,
termenv: &TermEnv,
vars: &mut HashMap<VarId, V::PatternId>,
) {
match self {
&Pattern::BindPattern(_ty, var, ref subpat) => {
// Bind the appropriate variable and recurse.
assert!(!vars.contains_key(&var));
vars.insert(var, input);
subpat.visit(visitor, input, termenv, vars);
}
&Pattern::Var(ty, var) => {
// Assert that the value matches the existing bound var.
let var_val = vars
.get(&var)
.copied()
.expect("Variable should already be bound");
visitor.add_match_equal(input, var_val, ty);
}
&Pattern::ConstInt(ty, value) => visitor.add_match_int(input, ty, value),
&Pattern::ConstPrim(ty, value) => visitor.add_match_prim(input, ty, value),
&Pattern::Term(ty, term, ref args) => {
// Determine whether the term has an external extractor or not.
let termdata = &termenv.terms[term.index()];
let arg_values = match &termdata.kind {
TermKind::EnumVariant { variant } => {
visitor.add_match_variant(input, ty, &termdata.arg_tys, *variant)
}
TermKind::Decl {
extractor_kind: None,
..
} => {
panic!("Pattern invocation of undefined term body")
}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { .. }),
..
} => {
panic!("Should have been expanded away")
}
TermKind::Decl {
multi,
extractor_kind: Some(ExtractorKind::ExternalExtractor { infallible, .. }),
..
} => {
// Evaluate all `input` args.
let output_tys = args.iter().map(|arg| arg.ty()).collect();
// Invoke the extractor.
visitor.add_extract(
input,
termdata.ret_ty,
output_tys,
term,
*infallible && !*multi,
*multi,
)
}
};
for (pat, val) in args.iter().zip(arg_values) {
pat.visit(visitor, val, termenv, vars);
}
}
&Pattern::And(_ty, ref children) => {
for child in children {
child.visit(visitor, input, termenv, vars);
}
}
&Pattern::Wildcard(_ty) => {
// Nothing!
}
}
}
}
/// Visitor interface for [Expr]s. Visitors can return an arbitrary identifier for each
/// subexpression, which is threaded through to subsequent calls into the visitor.
pub trait ExprVisitor {
/// The type of subexpression identifiers.
type ExprId: Copy;
/// Construct a constant integer.
fn add_const_int(&mut self, ty: TypeId, val: i128) -> Self::ExprId;
/// Construct a primitive constant.
fn add_const_prim(&mut self, ty: TypeId, val: Sym) -> Self::ExprId;
/// Construct an enum variant with the given `inputs` assigned to the variant's fields in order.
fn add_create_variant(
&mut self,
inputs: Vec<(Self::ExprId, TypeId)>,
ty: TypeId,
variant: VariantId,
) -> Self::ExprId;
/// Call an external constructor with the given `inputs` as arguments.
fn add_construct(
&mut self,
inputs: Vec<(Self::ExprId, TypeId)>,
ty: TypeId,
term: TermId,
infallible: bool,
multi: bool,
) -> Self::ExprId;
}
impl Expr {
/// Get this expression's type.
pub fn ty(&self) -> TypeId {
match self {
&Self::Term(t, ..) => t,
&Self::Var(t, ..) => t,
&Self::ConstInt(t, ..) => t,
&Self::ConstPrim(t, ..) => t,
&Self::Let { ty: t, .. } => t,
}
}
/// Recursively visit every subexpression.
pub fn visit<V: ExprVisitor>(
&self,
visitor: &mut V,
termenv: &TermEnv,
vars: &HashMap<VarId, V::ExprId>,
) -> V::ExprId {
log!("Expr::visit: expr {:?}", self);
match self {
&Expr::ConstInt(ty, val) => visitor.add_const_int(ty, val),
&Expr::ConstPrim(ty, val) => visitor.add_const_prim(ty, val),
&Expr::Let {
ty: _ty,
ref bindings,
ref body,
} => {
let mut vars = vars.clone();
for &(var, _var_ty, ref var_expr) in bindings {
let var_value = var_expr.visit(visitor, termenv, &vars);
vars.insert(var, var_value);
}
body.visit(visitor, termenv, &vars)
}
&Expr::Var(_ty, var_id) => *vars.get(&var_id).unwrap(),
&Expr::Term(ty, term, ref arg_exprs) => {
let termdata = &termenv.terms[term.index()];
let arg_values_tys = arg_exprs
.iter()
.map(|arg_expr| arg_expr.visit(visitor, termenv, vars))
.zip(termdata.arg_tys.iter().copied())
.collect();
match &termdata.kind {
TermKind::EnumVariant { variant } => {
visitor.add_create_variant(arg_values_tys, ty, *variant)
}
TermKind::Decl {
constructor_kind: Some(ConstructorKind::InternalConstructor),
multi,
..
} => {
visitor.add_construct(
arg_values_tys,
ty,
term,
/* infallible = */ false,
*multi,
)
}
TermKind::Decl {
constructor_kind: Some(ConstructorKind::ExternalConstructor { .. }),
pure,
multi,
..
} => {
visitor.add_construct(
arg_values_tys,
ty,
term,
/* infallible = */ !pure,
*multi,
)
}
TermKind::Decl {
constructor_kind: None,
..
} => panic!("Should have been caught by typechecking"),
}
}
}
}
fn visit_in_rule<V: RuleVisitor>(
&self,
visitor: &mut V,
termenv: &TermEnv,
vars: &HashMap<VarId, <V::PatternVisitor as PatternVisitor>::PatternId>,
) -> V::Expr {
let var_exprs = vars
.iter()
.map(|(&var, &val)| (var, visitor.pattern_as_expr(val)))
.collect();
visitor.add_expr(|visitor| VisitedExpr {
ty: self.ty(),
value: self.visit(visitor, termenv, &var_exprs),
})
}
}
/// Information about an expression after it has been fully visited in [RuleVisitor::add_expr].
#[derive(Clone, Copy)]
pub struct VisitedExpr<V: ExprVisitor> {
/// The type of the top-level expression.
pub ty: TypeId,
/// The identifier returned by the visitor for the top-level expression.
pub value: V::ExprId,
}
/// Visitor interface for [Rule]s. Visitors must be able to visit patterns by implementing
/// [PatternVisitor], and to visit expressions by providing a type that implements [ExprVisitor].
pub trait RuleVisitor {
/// The type of pattern visitors constructed by [RuleVisitor::add_pattern].
type PatternVisitor: PatternVisitor;
/// The type of expression visitors constructed by [RuleVisitor::add_expr].
type ExprVisitor: ExprVisitor;
/// The type returned from [RuleVisitor::add_expr], which may be exchanged for a subpattern
/// identifier using [RuleVisitor::expr_as_pattern].
type Expr;
/// Visit one of the arguments to the top-level pattern.
fn add_arg(
&mut self,
index: usize,
ty: TypeId,
) -> <Self::PatternVisitor as PatternVisitor>::PatternId;
/// Visit a pattern, used once for the rule's left-hand side and once for each if-let. You can
/// determine which part of the rule the pattern comes from based on whether the `PatternId`
/// passed to the first call to this visitor came from `add_arg` or `expr_as_pattern`.
fn add_pattern<F>(&mut self, visitor: F)
where
F: FnOnce(&mut Self::PatternVisitor);
/// Visit an expression, used once for each if-let and once for the rule's right-hand side.
fn add_expr<F>(&mut self, visitor: F) -> Self::Expr
where
F: FnOnce(&mut Self::ExprVisitor) -> VisitedExpr<Self::ExprVisitor>;
/// Given an expression from [RuleVisitor::add_expr], return an identifier that can be used with
/// a pattern visitor in [RuleVisitor::add_pattern].
fn expr_as_pattern(
&mut self,
expr: Self::Expr,
) -> <Self::PatternVisitor as PatternVisitor>::PatternId;
/// Given an identifier from the pattern visitor, return an identifier that can be used with
/// the expression visitor.
fn pattern_as_expr(
&mut self,
pattern: <Self::PatternVisitor as PatternVisitor>::PatternId,
) -> <Self::ExprVisitor as ExprVisitor>::ExprId;
}
impl Rule {
/// Recursively visit every pattern and expression in this rule. Returns the [RuleVisitor::Expr]
/// that was returned from [RuleVisitor::add_expr] when that function was called on the rule's
/// right-hand side.
pub fn visit<V: RuleVisitor>(&self, visitor: &mut V, termenv: &TermEnv) -> V::Expr {
let mut vars = HashMap::new();
// Visit the pattern, starting from the root input value.
let termdata = &termenv.terms[self.root_term.index()];
for (i, (subpat, &arg_ty)) in self.args.iter().zip(termdata.arg_tys.iter()).enumerate() {
let value = visitor.add_arg(i, arg_ty);
visitor.add_pattern(|visitor| subpat.visit(visitor, value, termenv, &mut vars));
}
// Visit the `if-let` clauses, using `V::ExprVisitor` for the sub-exprs (right-hand sides).
for iflet in self.iflets.iter() {
let subexpr = iflet.rhs.visit_in_rule(visitor, termenv, &vars);
let value = visitor.expr_as_pattern(subexpr);
visitor.add_pattern(|visitor| iflet.lhs.visit(visitor, value, termenv, &mut vars));
}
// Visit the rule's right-hand side, making use of the bound variables from the pattern.
self.rhs.visit_in_rule(visitor, termenv, &vars)
}