diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/mir/from_hir_match.cpp | 1960 |
1 files changed, 3 insertions, 1957 deletions
diff --git a/src/mir/from_hir_match.cpp b/src/mir/from_hir_match.cpp index 584e7dc0..ecc8b6e6 100644 --- a/src/mir/from_hir_match.cpp +++ b/src/mir/from_hir_match.cpp @@ -461,7 +461,7 @@ void MIR_LowerHIR_Match( MirBuilder& builder, MirConverter& conv, ::HIR::ExprNod } // TODO: Remove columns that are all `_`? - // - Ideally, only accessible structures would be fully destructured like this. + // - Ideally, only accessible structures would be fully destructured like this, making this check redundant // Sort rules using the following restrictions: // - A rule cannot be reordered across an item that has an overlapping match set @@ -497,13 +497,14 @@ void MIR_LowerHIR_Match( MirBuilder& builder, MirConverter& conv, ::HIR::ExprNod } // TODO: Don't generate inner code until decisions are generated (keeps MIR flow nice) + // - Challenging, as the decision code needs somewhere to jump to. + // - Allocating a BB and then rewriting references to it is a possibility. if( fall_back_on_simple ) { MIR_LowerHIR_Match_Simple( builder, conv, node, mv$(match_val), mv$(arm_rules), mv$(arm_code), first_cmp_block ); } else { MIR_LowerHIR_Match_Grouped( builder, conv, node, mv$(match_val), mv$(arm_rules), mv$(arm_code), first_cmp_block ); - //MIR_LowerHIR_Match_DecisionTree( builder, conv, node, mv$(match_val), mv$(arm_rules), mv$(arm_code), first_cmp_block ); } builder.set_cur_block( next_block ); @@ -3264,1958 +3265,3 @@ void MatchGenGrouped::gen_dispatch_splitslice(const field_path_t& field_path, co } } -// -------------------------------------------------------------------- -// Decision Tree -// -------------------------------------------------------------------- - -// ## Create descision tree in-memory based off the ruleset -// > Tree contains an lvalue and a set of possibilities (PatternRule) connected to another tree or to a branch index -struct DecisionTreeNode -{ - TAGGED_UNION( Branch, Unset, - (Unset, struct{}), - (Subtree, ::std::unique_ptr<DecisionTreeNode>), - (Terminal, unsigned int) - ); - - template<typename T> - struct Range - { - T start; - T end; - - // `x` starts after this range ends - bool operator<(const Range<T>& x) const { - return (end < x.start); - } - // `x` falls above the end of this range - bool operator<(const T& x) const { - return (end < x); - } - - // `x` ends before this starts, or overlaps - bool operator>=(const Range<T>& x) const { - return start > x.end || ovelaps(x); - } - // `x` is before or within this range - bool operator>=(const T& x) const { - return start > x || contains(x); - } - - bool operator>(const Range<T>& x) const { - return (start > x.end); - } - bool operator>(const T& x) const { - return (start > x); - } - - bool operator==(const Range<T>& x) const { - return start == x.start && end == x.end; - } - bool operator!=(const Range<T>& x) const { - return start != x.start || end != x.end; - } - - bool contains(const T& x) const { - return (start <= x && x <= end); - } - bool overlaps(const Range<T>& x) const { - return (x.start <= start && start <= x.end) || (x.start <= end && end <= x.end); - } - - friend ::std::ostream& operator<<(::std::ostream& os, const Range<T>& x) { - if( x.start == x.end ) { - return os << x.start; - } - else { - return os << x.start << " ... " << x.end; - } - } - }; - - TAGGED_UNION( Values, Unset, - (Unset, struct {}), - (Bool, struct { Branch false_branch, true_branch; }), - (Variant, ::std::vector< ::std::pair<unsigned int, Branch> >), - (Unsigned, ::std::vector< ::std::pair< Range<uint64_t>, Branch> >), - (Signed, ::std::vector< ::std::pair< Range<int64_t>, Branch> >), - (Float, ::std::vector< ::std::pair< Range<double>, Branch> >), - (String, ::std::vector< ::std::pair< ::std::string, Branch> >), - (Slice, struct { - ::std::vector< ::std::pair< unsigned int, Branch> > fixed_arms; - //::std::vector< ::std::pair< unsigned int, Branch> > variable_arms; - }) - ); - - // TODO: Arm specialisation? - field_path_t m_field_path; - Values m_branches; - Branch m_default; - - DecisionTreeNode( field_path_t field_path ): - // TODO: This is commented out fo a reason, but I don't know why. - //m_field_path( mv$(field_path) ), - m_branches(), - m_default() - {} - - static Branch clone(const Branch& b); - static Values clone(const Values& x); - DecisionTreeNode clone() const; - - void populate_tree_from_rule(const Span& sp, unsigned int arm_index, const PatternRule* first_rule, unsigned int rule_count) { - populate_tree_from_rule(sp, first_rule, rule_count, [sp,arm_index](auto& branch){ - TU_MATCHA( (branch), (e), - (Unset, - // Good - ), - (Subtree, - if( e->m_branches.is_Unset() && e->m_default.is_Unset() ) { - // Good. - } - else { - BUG(sp, "Duplicate terminal - branch="<<branch); - } - ), - (Terminal, - // TODO: This is ok if it's due to overlapping rules (e.g. ranges) - //BUG(sp, "Duplicate terminal - Existing goes to arm " << e << ", new goes to arm " << arm_index ); - ) - ) - branch = Branch::make_Terminal(arm_index); - }); - } - // `and_then` - Closure called after processing the final rule - void populate_tree_from_rule(const Span& sp, const PatternRule* first_rule, unsigned int rule_count, ::std::function<void(Branch&)> and_then); - - /// Simplifies the tree by eliminating nodes that don't make a decision - void simplify(); - /// Propagate the m_default arm's contents to value arms, and vice-versa - void propagate_default(); - /// HELPER: Unfies the rules from the provided branch with this node - void unify_from(const Branch& b); - - ::MIR::LValue get_field(const ::MIR::LValue& base, unsigned int base_depth) const { - ::MIR::LValue cur = base.clone(); - for(unsigned int i = base_depth; i < m_field_path.size(); i ++ ) { - const auto idx = m_field_path.data[i]; - if( idx == FIELD_DEREF ) { - cur = ::MIR::LValue::make_Deref({ box$(cur) }); - } - else { - cur = ::MIR::LValue::make_Field({ box$(cur), idx }); - } - } - return cur; - } - - friend ::std::ostream& operator<<(::std::ostream& os, const Branch& x); - friend ::std::ostream& operator<<(::std::ostream& os, const DecisionTreeNode& x); -}; - -struct DecisionTreeGen -{ - MirBuilder& m_builder; - const ::std::vector< ::MIR::BasicBlockId>& m_rule_blocks; - - DecisionTreeGen(MirBuilder& builder, const ::std::vector< ::MIR::BasicBlockId >& rule_blocks): - m_builder( builder ), - m_rule_blocks( rule_blocks ) - {} - - ::MIR::BasicBlockId get_block_for_rule(unsigned int rule_index) { - return m_rule_blocks.at( rule_index ); - } - - void generate_tree_code(const Span& sp, const DecisionTreeNode& node, const ::HIR::TypeRef& ty, const ::MIR::LValue& val) { - generate_tree_code(sp, node, ty, 0, val, [&](const auto& n){ - DEBUG("node = " << n); - // - Recurse on this method - this->generate_tree_code(sp, n, ty, val); - }); - } - void generate_tree_code( - const Span& sp, - const DecisionTreeNode& node, - const ::HIR::TypeRef& ty, unsigned int path_ofs, const ::MIR::LValue& base_val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - - void generate_branch(const DecisionTreeNode::Branch& branch, ::std::function<void(const DecisionTreeNode&)> cb); - - // HELPER - ::MIR::LValue push_compare(const Span& sp, ::MIR::LValue left, ::MIR::eBinOp op, ::MIR::Param right); - - void generate_branches_Signed( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Signed& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - void generate_branches_Unsigned( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Unsigned& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - void generate_branches_Float( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Float& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - void generate_branches_Char( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Unsigned& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - void generate_branches_Bool( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Bool& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - void generate_branches_Borrow_str( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_String& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - - void generate_branches_Enum( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Variant& branches, - const field_path_t& field_path, // used to know when to stop handling sub-nodes - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - void generate_branches_Slice( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Slice& branches, - const field_path_t& field_path, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ); - void generate_tree_code__enum( - const Span& sp, - const DecisionTreeNode& node, const ::HIR::TypeRef& fake_ty, const ::MIR::LValue& val, - const field_path_t& path_prefix, - ::std::function<void(const DecisionTreeNode&)> and_then - ); -}; - -void MIR_LowerHIR_Match_DecisionTree( MirBuilder& builder, MirConverter& conv, ::HIR::ExprNode_Match& node, ::MIR::LValue match_val, t_arm_rules arm_rules, ::std::vector<ArmCode> arms_code, ::MIR::BasicBlockId first_cmp_block ) -{ - TRACE_FUNCTION; - - // XXX XXX XXX: The current codegen (below) will generate incorrect code if ordering matters. - // ``` - // match ("foo", "bar") - // { - // (_, "bar") => {}, // Expected - // ("foo", _) => {}, // Actual - // _ => {}, - // } - // ``` - - // TODO: Sort the columns in `arm_rules` to ensure that the most specific rule is parsed first. - // - Ordering within a pattern doesn't matter, only the order of arms matters. - // - This sort could be designed such that the above case would match correctly? - - DEBUG("- Generating rule bindings"); - ::std::vector< ::MIR::BasicBlockId> rule_blocks; - for(const auto& rule : arm_rules) - { - const auto& arm_code = arms_code[rule.arm_idx]; - ASSERT_BUG(node.span(), !arm_code.has_condition, "Decision tree doesn't (yet) support conditionals"); - - assert( rule.pat_idx < arm_code.destructures.size() ); - // Set the target for when a rule succeeds to the destructuring code for this rule - rule_blocks.push_back( arm_code.destructures[rule.pat_idx] ); - // - Tie the end of that block to the code block for this arm - builder.set_cur_block( rule_blocks.back() ); - builder.end_block( ::MIR::Terminator::make_Goto(arm_code.code) ); - } - - - // - Build tree by running each arm's pattern across it - DEBUG("- Building decision tree"); - DecisionTreeNode root_node({}); - unsigned int rule_idx = 0; - for( const auto& arm_rule : arm_rules ) - { - auto arm_idx = arm_rule.arm_idx; - DEBUG("(" << arm_idx << ", " << arm_rule.pat_idx << "): " << arm_rule.m_rules); - root_node.populate_tree_from_rule( node.m_arms[arm_idx].m_code->span(), rule_idx, arm_rule.m_rules.data(), arm_rule.m_rules.size() ); - rule_idx += 1; - } - DEBUG("root_node = " << root_node); - root_node.simplify(); - DEBUG("root_node = " << root_node); - root_node.propagate_default(); - DEBUG("root_node = " << root_node); - // TODO: Pretty print `root_node` - - // - Convert the above decision tree into MIR - DEBUG("- Emitting decision tree"); - DecisionTreeGen gen { builder, rule_blocks }; - builder.set_cur_block( first_cmp_block ); - gen.generate_tree_code( node.span(), root_node, node.m_value->m_res_type, mv$(match_val) ); - ASSERT_BUG(node.span(), !builder.block_active(), "Decision tree didn't terminate the final block"); -} - -#if 0 -DecisionTreeNode MIR_LowerHIR_Match_DecisionTree__MakeTree(const Span& sp, t_arm_rules& arm_rules) -{ - ::std::vector<unsigned int> indexes; - ::std::vector< slice<PatternRule> > rules; - for(unsigned i = 0; i < arm_rules.size(); i ++) - { - rules.push_back( arm_rules[i].m_rules ); - indexes.push_back(i); - } - - return MIR_LowerHIR_Match_DecisionTree__MakeTree_Node(sp, indexes, rules); -} -DecisionTreeNode MIR_LowerHIR_Match_DecisionTree__MakeTree_Node(const Span& sp, slice<unsigned int> arm_indexes, slice< slice<PaternRule>> arm_rules) -{ - assert( arm_indexes.size() == arm_rules.size() ); - assert( arm_rules.size() > 1 ); - assert( arm_rules[0].size() > 0 ); - - // 1. Sort list (should it already be sorted?) - for(const auto& rules : arm_rules) - { - ASSERT_BUG(sp, rules.size() != arm_rules[0].size(), ""); - } - - // 2. Detect all arms being `_` and move on to the next condition - while( ::std::all_of(arm_rules.begin(), arm_rules.end(), [](const auto& r){ return r.m_rules[0].is_Any(); }) ) - { - // Delete first rule from all and continue. - if( arm_rules[0].size() == 1 ) { - // No rules left? - BUG(sp, "Duplicate match arms"); - } - - for(auto& rules : arm_rules) - { - rules = rules.subslice_from(1); - } - } - - // We have a codition. - for(const auto& rules : arm_rules) - { - ASSERT_BUG(sp, rules[0].is_Any() || rules[0].tag() == arm_rules[0][0].tag(), "Mismatched rules in match"); - } - - bool has_any = arm_rules.back()[0].is_Any(); - - // All rules must either be _ or the same type, and can't all be _ - switch( arm_rules[0][0].tag() ) - { - case PatternRule::TAGDEAD: throw ""; - case PatternRule::TAG_Any: throw ""; - - case PatternRule::TAG_Variant: - break; - // TODO: Value and ValueRange can appear together. - // - They also overlap in non-trivial ways. - } -} -#endif - -// ---------------------------- -// DecisionTreeNode -// ---------------------------- -DecisionTreeNode::Branch DecisionTreeNode::clone(const DecisionTreeNode::Branch& b) { - TU_MATCHA( (b), (e), - (Unset, return Branch(e); ), - (Subtree, return Branch(box$( e->clone() )); ), - (Terminal, return Branch(e); ) - ) - throw ""; -} -DecisionTreeNode::Values DecisionTreeNode::clone(const DecisionTreeNode::Values& x) { - TU_MATCHA( (x), (e), - (Unset, return Values(e); ), - (Bool, - return Values::make_Bool({ clone(e.false_branch), clone(e.true_branch) }); - ), - (Variant, - Values::Data_Variant rv; - rv.reserve(e.size()); - for(const auto& v : e) - rv.push_back( ::std::make_pair(v.first, clone(v.second)) ); - return Values( mv$(rv) ); - ), - (Unsigned, - Values::Data_Unsigned rv; - rv.reserve(e.size()); - for(const auto& v : e) - rv.push_back( ::std::make_pair(v.first, clone(v.second)) ); - return Values( mv$(rv) ); - ), - (Signed, - Values::Data_Signed rv; - rv.reserve(e.size()); - for(const auto& v : e) - rv.push_back( ::std::make_pair(v.first, clone(v.second)) ); - return Values( mv$(rv) ); - ), - (Float, - Values::Data_Float rv; - rv.reserve(e.size()); - for(const auto& v : e) - rv.push_back( ::std::make_pair(v.first, clone(v.second)) ); - return Values( mv$(rv) ); - ), - (String, - Values::Data_String rv; - rv.reserve(e.size()); - for(const auto& v : e) - rv.push_back( ::std::make_pair(v.first, clone(v.second)) ); - return Values( mv$(rv) ); - ), - (Slice, - Values::Data_Slice rv; - rv.fixed_arms.reserve(e.fixed_arms.size()); - for(const auto& v : e.fixed_arms) - rv.fixed_arms.push_back( ::std::make_pair(v.first, clone(v.second)) ); - return Values( mv$(rv) ); - ) - ) - throw ""; -} -DecisionTreeNode DecisionTreeNode::clone() const { - DecisionTreeNode rv(m_field_path); - rv.m_field_path = m_field_path; - rv.m_branches = clone(m_branches); - rv.m_default = clone(m_default); - return rv; -} - -// Helpers for `populate_tree_from_rule` -namespace -{ - DecisionTreeNode::Branch new_branch_subtree(field_path_t path) - { - return DecisionTreeNode::Branch( box$(DecisionTreeNode( mv$(path) )) ); - } - - // Common code for numerics (Int, Uint, and Float) - template<typename T> - static void from_rule_value( - const Span& sp, - ::std::vector< ::std::pair< DecisionTreeNode::Range<T>, DecisionTreeNode::Branch> >& be, T ve, - const char* name, const field_path_t& field_path, ::std::function<void(DecisionTreeNode::Branch&)> and_then - ) - { - auto it = ::std::find_if(be.begin(), be.end(), [&](const auto& v){ return v.first.end >= ve; }); - if( it == be.end() || it->first.start > ve ) { - it = be.insert( it, ::std::make_pair( DecisionTreeNode::Range<T> { ve,ve }, new_branch_subtree(field_path) ) ); - } - else if( it->first.start == ve && it->first.end == ve ) { - // Equal, continue and add sub-pat - } - else { - // Collide or overlap! - TODO(sp, "Value patterns - " << name << " - Overlapping - " << it->first.start << " <= " << ve << " <= " << it->first.end); - } - and_then( it->second ); - } - - template<typename T> - static void from_rule_valuerange( - const Span& sp, - ::std::vector< ::std::pair< DecisionTreeNode::Range<T>, DecisionTreeNode::Branch> >& be, T ve_start, T ve_end, - const char* name, const field_path_t& field_path, ::std::function<void(DecisionTreeNode::Branch&)> and_then - ) - { - TRACE_FUNCTION_F("be=[" << FMT_CB(os, for(const auto& i:be) os << i.first <<" , ";) << "], new=" << ve_start << "..." << ve_end); - ASSERT_BUG(sp, ve_start <= ve_end, "Range pattern with a start after the end - " << ve_start << "..." << ve_end); - - if( ve_start == ve_end ) { - from_rule_value(sp, be, ve_start, name, field_path, and_then); - return ; - } - // - Find the first entry that ends after the new one starts. - auto it = ::std::find_if(be.begin(), be.end(), [&](const auto& v){ return v.first.end >= ve_start; }); - while(ve_start < ve_end) - { - if( it == be.end() ) { - DEBUG("new = (" << ve_start << "..." << ve_end << "), exist=END"); - it = be.insert( it, ::std::make_pair( DecisionTreeNode::Range<T> { ve_start,ve_end }, new_branch_subtree(field_path) ) ); - and_then(it->second); - return ; - } - DEBUG("new = (" << ve_start << "..." << ve_end << "), exist=" << it->first); - // If the located entry starts after the end of this range - if( it->first.start >= ve_end ) { - DEBUG("- New free"); - it = be.insert( it, ::std::make_pair( DecisionTreeNode::Range<T> { ve_start,ve_end }, new_branch_subtree(field_path) ) ); - and_then(it->second); - return ; - } - // If this range is equal to the existing, just recurse into it - else if( it->first.start == ve_start && it->first.end == ve_end ) { - DEBUG("- Equal"); - and_then(it->second); - return ; - } - // If the new range starts before the start of this range, add a new entry before the existing one - else if( it->first.start > ve_start ) { - DEBUG("- New head, continue"); - it = be.insert( it, ::std::make_pair( DecisionTreeNode::Range<T> { ve_start,it->first.start-1 }, new_branch_subtree(field_path) ) ); - and_then(it->second); - ++ it; - ve_start = it->first.start; - } - // If the new range ends before the end of this range, split the existing range and recurse into the first - else if( it->first.end > ve_end ) { - DEBUG("- Inner"); - assert(ve_start == it->first.start); - it = be.insert( it, ::std::make_pair( DecisionTreeNode::Range<T> { ve_start, ve_end }, DecisionTreeNode::clone(it->second) ) ); - and_then(it->second); - (it+1)->first.start = ve_end+1; - return ; - } - // (else) if the new range ends after the end of this range, apply to the rest of this range and advance - else { - DEBUG("- Shared head, continue"); - //assert(it->first.start == ve_start); - assert((it->first.end) < ve_end); - - and_then(it->second); - ve_start = it->first.end + 1; - ++ it; - } - } - } -} -void DecisionTreeNode::populate_tree_from_rule(const Span& sp, const PatternRule* first_rule, unsigned int rule_count, ::std::function<void(Branch&)> and_then) -{ - assert( rule_count > 0 ); - const auto& rule = *first_rule; - - if( m_field_path.size() == 0 ) { - m_field_path = rule.field_path; - } - else { - ASSERT_BUG(sp, m_field_path == rule.field_path, "Patterns with mismatched field paths - " << m_field_path << " != " << rule.field_path); - } - - #define GET_BRANCHES(fld, var) (({if( fld.is_Unset() ) {\ - fld = Values::make_##var({}); \ - } \ - else if( !fld.is_##var() ) { \ - BUG(sp, "Mismatched rules - have " #var ", but have seen " << fld.tag_str()); \ - }}), \ - fld.as_##var()) - - - TU_MATCHA( (rule), (e), - (Any, { - if( rule_count == 1 ) - { - ASSERT_BUG(sp, !m_default.is_Terminal(), "Duplicate terminal rule"); - and_then(m_default); - } - else - { - if( m_default.is_Unset() ) { - m_default = new_branch_subtree(rule.field_path); - m_default.as_Subtree()->populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else TU_IFLET( Branch, m_default, Subtree, be, - be->populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - ) - else { - // NOTE: All lists processed as part of the same tree should be the same length - BUG(sp, "Duplicate terminal rule"); - } - } - // TODO: Should this also recurse into branches? - }), - (Variant, { - auto& be = GET_BRANCHES(m_branches, Variant); - - auto it = ::std::find_if( be.begin(), be.end(), [&](const auto& x){ return x.first >= e.idx; }); - // If this variant isn't yet processed, add a new subtree for it - if( it == be.end() || it->first != e.idx ) { - it = be.insert(it, ::std::make_pair(e.idx, new_branch_subtree(rule.field_path))); - assert( it->second.is_Subtree() ); - } - else { - if( it->second.is_Terminal() ) { - BUG(sp, "Duplicate terminal rule - " << it->second.as_Terminal()); - } - assert( !it->second.is_Unset() ); - assert( it->second.is_Subtree() ); - } - auto& subtree = *it->second.as_Subtree(); - - if( e.sub_rules.size() > 0 && rule_count > 1 ) - { - subtree.populate_tree_from_rule(sp, e.sub_rules.data(), e.sub_rules.size(), [&](auto& branch){ - TU_MATCH_DEF(Branch, (branch), (be), - ( - BUG(sp, "Duplicate terminator"); - ), - (Unset, - branch = new_branch_subtree(rule.field_path); - ), - (Subtree, - ) - ) - branch.as_Subtree()->populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - }); - } - else if( e.sub_rules.size() > 0) - { - subtree.populate_tree_from_rule(sp, e.sub_rules.data(), e.sub_rules.size(), and_then); - } - else if( rule_count > 1 ) - { - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(it->second); - } - }), - (Slice, - auto& be = GET_BRANCHES(m_branches, Slice); - - auto it = ::std::find_if( be.fixed_arms.begin(), be.fixed_arms.end(), [&](const auto& x){ return x.first >= e.len; } ); - if( it == be.fixed_arms.end() || it->first != e.len ) { - it = be.fixed_arms.insert(it, ::std::make_pair(e.len, new_branch_subtree(rule.field_path))); - } - else { - if( it->second.is_Terminal() ) { - BUG(sp, "Duplicate terminal rule - " << it->second.as_Terminal()); - } - assert( !it->second.is_Unset() ); - } - assert( it->second.is_Subtree() ); - auto& subtree = *it->second.as_Subtree(); - - if( e.sub_rules.size() > 0 && rule_count > 1 ) - { - subtree.populate_tree_from_rule(sp, e.sub_rules.data(), e.sub_rules.size(), [&](auto& branch){ - TU_MATCH_DEF(Branch, (branch), (be), - ( - BUG(sp, "Duplicate terminator"); - ), - (Unset, - branch = new_branch_subtree(rule.field_path); - ), - (Subtree, - ) - ) - branch.as_Subtree()->populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - }); - } - else if( e.sub_rules.size() > 0) - { - subtree.populate_tree_from_rule(sp, e.sub_rules.data(), e.sub_rules.size(), and_then); - } - else if( rule_count > 1 ) - { - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(it->second); - } - ), - (SplitSlice, - //auto& be = GET_BRANCHES(m_branches, Slice); - TODO(sp, "SplitSlice in DTN - " << rule); - ), - (Bool, - auto& be = GET_BRANCHES(m_branches, Bool); - - auto& branch = (e ? be.true_branch : be.false_branch); - if( branch.is_Unset() ) { - branch = new_branch_subtree( rule.field_path ); - } - else if( branch.is_Terminal() ) { - BUG(sp, "Duplicate terminal rule - " << branch.as_Terminal()); - } - else { - // Good. - } - if( rule_count > 1 ) - { - auto& subtree = *branch.as_Subtree(); - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(branch); - } - ), - (Value, - TU_MATCHA( (e), (ve), - (Int, - auto& be = GET_BRANCHES(m_branches, Signed); - - from_rule_value(sp, be, ve.v, "Signed", rule.field_path, - [&](auto& branch) { - if( rule_count > 1 ) { - assert( branch.as_Subtree() ); - auto& subtree = *branch.as_Subtree(); - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(branch); - } - }); - ), - (Uint, - auto& be = GET_BRANCHES(m_branches, Unsigned); - - from_rule_value(sp, be, ve.v, "Unsigned", rule.field_path, - [&](auto& branch) { - if( rule_count > 1 ) { - assert( branch.as_Subtree() ); - auto& subtree = *branch.as_Subtree(); - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(branch); - } - }); - ), - (Float, - auto& be = GET_BRANCHES(m_branches, Float); - - from_rule_value(sp, be, ve.v, "Float", rule.field_path, - [&](auto& branch) { - if( rule_count > 1 ) { - assert( branch.as_Subtree() ); - auto& subtree = *branch.as_Subtree(); - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else { - and_then(branch); - } - }); - ), - (Bool, - BUG(sp, "Hit Bool in PatternRule::Value - " << e); - ), - (Bytes, - TODO(sp, "Value patterns - Bytes"); - ), - (StaticString, - auto& be = GET_BRANCHES(m_branches, String); - - auto it = ::std::find_if(be.begin(), be.end(), [&](const auto& v){ return v.first >= ve; }); - if( it == be.end() || it->first != ve ) { - it = be.insert( it, ::std::make_pair(ve, new_branch_subtree(rule.field_path) ) ); - } - auto& branch = it->second; - if( rule_count > 1 ) - { - assert( branch.as_Subtree() ); - auto& subtree = *branch.as_Subtree(); - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(branch); - } - ), - (Const, - BUG(sp, "Hit Const in PatternRule::Value - " << e); - ), - (ItemAddr, - BUG(sp, "Hit ItemAddr in PatternRule::Value - " << e); - ) - ) - ), - (ValueRange, - - ASSERT_BUG(sp, e.first.tag() == e.last.tag(), "Constant type mismatch in ValueRange - " << e.first << " and " << e.last); - TU_MATCHA( (e.first, e.last), (ve_start, ve_end), - (Int, - auto& be = GET_BRANCHES(m_branches, Signed); - from_rule_valuerange(sp, be, ve_start.v, ve_end.v, "Signed", rule.field_path, - [&](auto& branch) { - if( rule_count > 1 ) - { - assert( branch.as_Subtree() ); - auto& subtree = *branch.as_Subtree(); - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(branch); - } - }); - ), - (Uint, - // TODO: Share code between the three numeric groups - auto& be = GET_BRANCHES(m_branches, Unsigned); - from_rule_valuerange(sp, be, ve_start.v, ve_end.v, "Unsigned", rule.field_path, - [&](auto& branch) { - if( rule_count > 1 ) - { - assert( branch.as_Subtree() ); - auto& subtree = *branch.as_Subtree(); - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(branch); - } - }); - ), - (Float, - auto& be = GET_BRANCHES(m_branches, Float); - from_rule_valuerange(sp, be, ve_start.v, ve_end.v, "Float", rule.field_path, - [&](auto& branch) { - if( rule_count > 1 ) - { - assert( branch.as_Subtree() ); - auto& subtree = *branch.as_Subtree(); - subtree.populate_tree_from_rule(sp, first_rule+1, rule_count-1, and_then); - } - else - { - and_then(branch); - } - }); - ), - (Bool, - BUG(sp, "Hit Bool in PatternRule::ValueRange - " << e.first); - ), - (Bytes, - TODO(sp, "ValueRange patterns - Bytes"); - ), - (StaticString, - ERROR(sp, E0000, "Use of string in value range patter"); - ), - (Const, - BUG(sp, "Hit Const in PatternRule::ValueRange - " << e.first); - ), - (ItemAddr, - BUG(sp, "Hit ItemAddr in PatternRule::ValueRange - " << e.first); - ) - ) - ) - ) -} - -void DecisionTreeNode::simplify() -{ - struct H { - static void simplify_branch(Branch& b) - { - TU_IFLET(Branch, b, Subtree, be, - be->simplify(); - if( be->m_branches.is_Unset() ) { - auto v = mv$( be->m_default ); - b = mv$(v); - } - ) - } - }; - - TU_MATCHA( (m_branches), (e), - (Unset, - H::simplify_branch(m_default); - // Replace `this` with `m_default` if `m_default` is a subtree - // - Fixes the edge case for the top of the tree - if( m_default.is_Subtree() ) - { - *this = mv$(*m_default.as_Subtree()); - } - return ; - ), - (Bool, - H::simplify_branch(e.false_branch); - H::simplify_branch(e.true_branch); - ), - (Variant, - for(auto& branch : e) { - H::simplify_branch(branch.second); - } - ), - (Unsigned, - for(auto& branch : e) { - H::simplify_branch(branch.second); - } - ), - (Signed, - for(auto& branch : e) { - H::simplify_branch(branch.second); - } - ), - (Float, - for(auto& branch : e) { - H::simplify_branch(branch.second); - } - ), - (String, - for(auto& branch : e) { - H::simplify_branch(branch.second); - } - ), - (Slice, - for(auto& branch : e.fixed_arms) { - H::simplify_branch(branch.second); - } - ) - ) - - H::simplify_branch(m_default); -} - -void DecisionTreeNode::propagate_default() -{ - TRACE_FUNCTION_FR(*this, *this); - struct H { - static void handle_branch(Branch& b, const Branch& def) { - TU_IFLET(Branch, b, Subtree, be, - be->propagate_default(); - if( !def.is_Unset() ) - { - DEBUG("Unify " << *be << " with " << def); - be->unify_from(def); - be->propagate_default(); - } - ) - } - }; - - TU_MATCHA( (m_branches), (e), - (Unset, - ), - (Bool, - DEBUG("- false"); - H::handle_branch(e.false_branch, m_default); - DEBUG("- true"); - H::handle_branch(e.true_branch, m_default); - ), - (Variant, - for(auto& branch : e) { - DEBUG("- V " << branch.first); - H::handle_branch(branch.second, m_default); - } - ), - (Unsigned, - for(auto& branch : e) { - DEBUG("- U " << branch.first); - H::handle_branch(branch.second, m_default); - } - ), - (Signed, - for(auto& branch : e) { - DEBUG("- S " << branch.first); - H::handle_branch(branch.second, m_default); - } - ), - (Float, - for(auto& branch : e) { - DEBUG("- " << branch.first); - H::handle_branch(branch.second, m_default); - } - ), - (String, - for(auto& branch : e) { - DEBUG("- '" << branch.first << "'"); - H::handle_branch(branch.second, m_default); - } - ), - (Slice, - for(auto& branch : e.fixed_arms) { - DEBUG("- [_;" << branch.first << "]"); - H::handle_branch(branch.second, m_default); - } - ) - ) - DEBUG("- default"); - TU_IFLET(Branch, m_default, Subtree, be, - be->propagate_default(); - - if( be->m_default.is_Unset() ) { - // Propagate default from value branches - TU_MATCHA( (m_branches), (e), - (Unset, - ), - (Bool, - be->unify_from(e.false_branch); - be->unify_from(e.true_branch); - ), - (Variant, - for(auto& branch : e) { - be->unify_from(branch.second); - } - ), - (Unsigned, - for(auto& branch : e) { - be->unify_from(branch.second); - } - ), - (Signed, - for(auto& branch : e) { - be->unify_from(branch.second); - } - ), - (Float, - for(auto& branch : e) { - be->unify_from(branch.second); - } - ), - (String, - for(auto& branch : e) { - be->unify_from(branch.second); - } - ), - (Slice, - for(auto& branch : e.fixed_arms) { - be->unify_from(branch.second); - } - ) - ) - } - ) -} - -namespace { - static void unify_branch(DecisionTreeNode::Branch& dst, const DecisionTreeNode::Branch& src) { - if( dst.is_Unset() ) { - dst = DecisionTreeNode::clone(src); - } - else if( dst.is_Subtree() ) { - dst.as_Subtree()->unify_from(src); - } - else { - // Terminal, no unify - } - } - - template<typename T> - void unify_from_vals_range(::std::vector< ::std::pair<T, DecisionTreeNode::Branch>>& dst, const ::std::vector< ::std::pair<T, DecisionTreeNode::Branch>>& src) - { - for(const auto& srcv : src) - { - // Find the first entry with an end greater than or equal to the start of this entry - auto it = ::std::find_if( dst.begin(), dst.end(), [&](const auto& x){ return x.first.end >= srcv.first.start; }); - // Not found? Insert a new branch - if( it == dst.end() ) { - it = dst.insert(it, ::std::make_pair(srcv.first, DecisionTreeNode::clone(srcv.second))); - } - // If the found entry doesn't overlap (the start of `*it` is after the end of `srcv`) - else if( it->first.start > srcv.first.end ) { - it = dst.insert(it, ::std::make_pair(srcv.first, DecisionTreeNode::clone(srcv.second))); - } - else if( it->first == srcv.first ) { - unify_branch( it->second, srcv.second ); - } - else { - // NOTE: Overlapping doesn't get handled here - } - } - } - - template<typename T> - void unify_from_vals_pt(::std::vector< ::std::pair<T, DecisionTreeNode::Branch>>& dst, const ::std::vector< ::std::pair<T, DecisionTreeNode::Branch>>& src) - { - // Insert items not already present, merge present items - for(const auto& srcv : src) - { - auto it = ::std::find_if( dst.begin(), dst.end(), [&](const auto& x){ return x.first >= srcv.first; }); - // Not found? Insert a new branch - if( it == dst.end() || it->first != srcv.first ) { - it = dst.insert(it, ::std::make_pair(srcv.first, DecisionTreeNode::clone(srcv.second))); - } - else { - unify_branch( it->second, srcv.second ); - } - } - } -} - -void DecisionTreeNode::unify_from(const Branch& b) -{ - TRACE_FUNCTION_FR(*this << " with " << b, *this); - - assert( b.is_Terminal() || b.is_Subtree() ); - - if( m_default.is_Unset() ) { - if( b.is_Terminal() ) { - m_default = clone(b); - } - else { - m_default = clone(b.as_Subtree()->m_default); - } - } - - if( b.is_Subtree() && b.as_Subtree()->m_branches.tag() != m_branches.tag() ) { - // Is this a bug, or expected (and don't unify in?) - DEBUG("TODO - Unify mismatched arms? - " << b.as_Subtree()->m_branches.tag_str() << " and " << m_branches.tag_str()); - return ; - } - bool should_unify_subtree = b.is_Subtree() && this->m_field_path == b.as_Subtree()->m_field_path; - //if( b.is_Subtree() ) { - // ASSERT_BUG(Span(), this->m_field_path == b.as_Subtree()->m_field_path, "Unifiying DTNs with mismatched paths - " << this->m_field_path << " != " << b.as_Subtree()->m_field_path); - //} - - TU_MATCHA( (m_branches), (dst), - (Unset, - if( b.is_Subtree() ) { - assert( b.as_Subtree()->m_branches.is_Unset() ); - } - else { - // Huh? Terminal matching against an unset branch? - } - ), - (Bool, - auto* src = (b.is_Subtree() ? &b.as_Subtree()->m_branches.as_Bool() : nullptr); - - unify_branch( dst.false_branch, (src ? src->false_branch : b) ); - unify_branch( dst.true_branch , (src ? src->true_branch : b) ); - ), - (Variant, - if( should_unify_subtree ) { - auto& sb = b.as_Subtree()->m_branches; - ASSERT_BUG(Span(), sb.is_Variant(), "Unifying Variant with " << sb.tag_str()); - unify_from_vals_pt(dst, sb.as_Variant()); - } - else { - // Unify all with terminal branch - for(auto& dstv : dst) - { - unify_branch(dstv.second, b); - } - } - ), - (Unsigned, - if( should_unify_subtree ) { - auto& sb = b.as_Subtree()->m_branches; - ASSERT_BUG(Span(), sb.is_Unsigned(), "Unifying Unsigned with " << sb.tag_str()); - unify_from_vals_range(dst, sb.as_Unsigned()); - } - else { - for(auto& dstv : dst) - { - unify_branch(dstv.second, b); - } - } - ), - (Signed, - if( should_unify_subtree ) { - auto& sb = b.as_Subtree()->m_branches; - ASSERT_BUG(Span(), sb.is_Signed(), "Unifying Signed with " << sb.tag_str()); - unify_from_vals_range(dst, sb.as_Signed()); - } - else { - for(auto& dstv : dst) - { - unify_branch(dstv.second, b); - } - } - ), - (Float, - if( should_unify_subtree ) { - auto& sb = b.as_Subtree()->m_branches; - ASSERT_BUG(Span(), sb.is_Float(), "Unifying Float with " << sb.tag_str()); - unify_from_vals_range(dst, sb.as_Float()); - } - else { - for(auto& dstv : dst) { - unify_branch(dstv.second, b); - } - } - ), - (String, - if( should_unify_subtree ) { - auto& sb = b.as_Subtree()->m_branches; - ASSERT_BUG(Span(), sb.is_String(), "Unifying String with " << sb.tag_str()); - unify_from_vals_pt(dst, sb.as_String()); - } - else { - for(auto& dstv : dst) { - unify_branch( dstv.second, b ); - } - } - ), - (Slice, - if( should_unify_subtree ) { - auto& sb = b.as_Subtree()->m_branches; - ASSERT_BUG(Span(), sb.is_Slice(), "Unifying Slice with " << sb.tag_str()); - - const auto& src = sb.as_Slice(); - unify_from_vals_pt(dst.fixed_arms, src.fixed_arms); - } - else { - for(auto& dstv : dst.fixed_arms) { - unify_branch( dstv.second, b ); - } - } - ) - ) -} - -::std::ostream& operator<<(::std::ostream& os, const DecisionTreeNode::Branch& x) { - TU_MATCHA( (x), (be), - (Unset, - os << "!"; - ), - (Terminal, - os << "ARM " << be; - ), - (Subtree, - os << *be; - ) - ) - return os; -} -::std::ostream& operator<<(::std::ostream& os, const DecisionTreeNode& x) { - os << "DTN [" << x.m_field_path << "] { "; - TU_MATCHA( (x.m_branches), (e), - (Unset, - os << "!, "; - ), - (Bool, - os << "false = " << e.false_branch << ", true = " << e.true_branch << ", "; - ), - (Variant, - os << "V "; - for(const auto& branch : e) { - os << branch.first << " = " << branch.second << ", "; - } - ), - (Unsigned, - os << "U "; - for(const auto& branch : e) { - const auto& range = branch.first; - if( range.start == range.end ) { - os << range.start; - } - else { - os << range.start << "..." << range.end; - } - os << " = " << branch.second << ", "; - } - ), - (Signed, - os << "S "; - for(const auto& branch : e) { - const auto& range = branch.first; - if( range.start == range.end ) { - os << range.start; - } - else { - os << range.start << "..." << range.end; - } - os << " = " << branch.second << ", "; - } - ), - (Float, - os << "F "; - for(const auto& branch : e) { - const auto& range = branch.first; - if( range.start == range.end ) { - os << range.start; - } - else { - os << range.start << "..." << range.end; - } - os << " = " << branch.second << ", "; - } - ), - (String, - for(const auto& branch : e) { - os << "\"" << branch.first << "\"" << " = " << branch.second << ", "; - } - ), - (Slice, - os << "len "; - for(const auto& branch : e.fixed_arms) { - os << "=" << branch.first << " = " << branch.second << ", "; - } - ) - ) - - os << "* = " << x.m_default; - os << " }"; - return os; -} - - -// ---------------------------- -// DecisionTreeGen -// ---------------------------- - -void DecisionTreeGen::generate_tree_code( - const Span& sp, - const DecisionTreeNode& node, - const ::HIR::TypeRef& top_ty, unsigned int field_path_ofs, const ::MIR::LValue& top_val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - TRACE_FUNCTION_F("top_ty=" << top_ty << ", field_path_ofs=" << field_path_ofs << ", top_val=" << top_val << ", node=" << node); - - ::MIR::LValue val; - ::HIR::TypeRef ty; - - get_ty_and_val(sp, m_builder.resolve(), top_ty, top_val, node.m_field_path, field_path_ofs, ty, val); - DEBUG("ty = " << ty << ", val = " << val); - - TU_MATCHA( (ty.m_data), (e), - (Infer, BUG(sp, "Ivar for in match type"); ), - (Diverge, BUG(sp, "Diverge in match type"); ), - (Primitive, - switch(e) - { - case ::HIR::CoreType::Bool: - ASSERT_BUG(sp, node.m_branches.is_Bool(), "Tree for bool isn't a _Bool - node="<<node); - this->generate_branches_Bool(sp, node.m_default, node.m_branches.as_Bool(), ty, mv$(val), mv$(and_then)); - break; - case ::HIR::CoreType::U8: - case ::HIR::CoreType::U16: - case ::HIR::CoreType::U32: - case ::HIR::CoreType::U64: - case ::HIR::CoreType::U128: - case ::HIR::CoreType::Usize: - ASSERT_BUG(sp, node.m_branches.is_Unsigned(), "Tree for unsigned isn't a _Unsigned - node="<<node); - this->generate_branches_Unsigned(sp, node.m_default, node.m_branches.as_Unsigned(), ty, mv$(val), mv$(and_then)); - break; - case ::HIR::CoreType::I8: - case ::HIR::CoreType::I16: - case ::HIR::CoreType::I32: - case ::HIR::CoreType::I64: - case ::HIR::CoreType::I128: - case ::HIR::CoreType::Isize: - ASSERT_BUG(sp, node.m_branches.is_Signed(), "Tree for unsigned isn't a _Signed - node="<<node); - this->generate_branches_Signed(sp, node.m_default, node.m_branches.as_Signed(), ty, mv$(val), mv$(and_then)); - break; - case ::HIR::CoreType::Char: - ASSERT_BUG(sp, node.m_branches.is_Unsigned(), "Tree for char isn't a _Unsigned - node="<<node); - this->generate_branches_Char(sp, node.m_default, node.m_branches.as_Unsigned(), ty, mv$(val), mv$(and_then)); - break; - case ::HIR::CoreType::Str: - ASSERT_BUG(sp, node.m_branches.is_String(), "Tree for &str isn't a _String - node="<<node); - this->generate_branches_Borrow_str(sp, node.m_default, node.m_branches.as_String(), ty, mv$(val), mv$(and_then)); - break; - case ::HIR::CoreType::F32: - case ::HIR::CoreType::F64: - ASSERT_BUG(sp, node.m_branches.is_Float(), "Tree for float isn't a _Float - node="<<node); - this->generate_branches_Float(sp, node.m_default, node.m_branches.as_Float(), ty, mv$(val), mv$(and_then)); - break; - default: - TODO(sp, "Primitive - " << ty); - break; - } - ), - (Tuple, - BUG(sp, "Decision node on tuple - node=" << node); - ), - (Path, - // This is either a struct destructure or an enum - TU_MATCHA( (e.binding), (pbe), - (Unbound, - BUG(sp, "Encounterd unbound path - " << e.path); - ), - (Opaque, - and_then(node); - ), - (Struct, - assert(pbe); - TU_MATCHA( (pbe->m_data), (fields), - (Unit, - and_then(node); - ), - (Tuple, - BUG(sp, "Decision node on tuple struct"); - ), - (Named, - BUG(sp, "Decision node on struct"); - ) - ) - ), - (Union, - TODO(sp, "Decision node on Union"); - ), - (Enum, - ASSERT_BUG(sp, node.m_branches.is_Variant(), "Tree for enum isn't a Variant - node="<<node); - assert(pbe); - this->generate_branches_Enum(sp, node.m_default, node.m_branches.as_Variant(), node.m_field_path, ty, mv$(val), mv$(and_then)); - ) - ) - ), - (Generic, - and_then(node); - ), - (TraitObject, - ERROR(sp, E0000, "Attempting to match over a trait object"); - ), - (ErasedType, - ERROR(sp, E0000, "Attempting to match over an erased type"); - ), - (Array, - // TODO: Slice patterns, sequential comparison/sub-match - TODO(sp, "Match over array"); - ), - (Slice, - ASSERT_BUG(sp, node.m_branches.is_Slice(), "Tree for [T] isn't a _Slice - node="<<node); - this->generate_branches_Slice(sp, node.m_default, node.m_branches.as_Slice(), node.m_field_path, ty, mv$(val), mv$(and_then)); - ), - (Borrow, - if( *e.inner == ::HIR::CoreType::Str ) { - TODO(sp, "Match over &str"); - } - else { - BUG(sp, "Decision node on non-str/[T] borrow - " << ty); - } - ), - (Pointer, - ERROR(sp, E0000, "Attempting to match over a pointer"); - ), - (Function, - ERROR(sp, E0000, "Attempting to match over a functon pointer"); - ), - (Closure, - ERROR(sp, E0000, "Attempting to match over a closure"); - ) - ) -} - -void DecisionTreeGen::generate_branch(const DecisionTreeNode::Branch& branch, ::std::function<void(const DecisionTreeNode&)> cb) -{ - assert( !branch.is_Unset() ); - if( branch.is_Terminal() ) { - this->m_builder.end_block( ::MIR::Terminator::make_Goto( this->get_block_for_rule( branch.as_Terminal() ) ) ); - } - else { - assert( branch.is_Subtree() ); - const auto& subnode = *branch.as_Subtree(); - - cb(subnode); - } -} - -::MIR::LValue DecisionTreeGen::push_compare(const Span& sp, ::MIR::LValue left, ::MIR::eBinOp op, ::MIR::Param right) -{ - return m_builder.lvalue_or_temp(sp, ::HIR::CoreType::Bool, - ::MIR::RValue::make_BinOp({ mv$(left), op, mv$(right) }) - ); -} - -// TODO: Unify logic for these two, and support simpler checks for sequential values -void DecisionTreeGen::generate_branches_Signed( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Signed& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - auto ity = ty.m_data.as_Primitive(); - auto default_block = m_builder.new_bb_unlinked(); - - // TODO: Convert into an integer switch w/ offset instead of chained comparisons - - for( const auto& branch : branches ) - { - auto next_block = (&branch == &branches.back() ? default_block : m_builder.new_bb_unlinked()); - - auto cmp_gt_block = m_builder.new_bb_unlinked(); - auto val_cmp_lt = push_compare(sp, val.clone(), ::MIR::eBinOp::LT, ::MIR::Constant::make_Int({ branch.first.start, ity })); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_lt), default_block, cmp_gt_block }) ); - m_builder.set_cur_block( cmp_gt_block ); - - auto success_block = m_builder.new_bb_unlinked(); - auto val_cmp_gt = push_compare(sp, val.clone(), ::MIR::eBinOp::GT, ::MIR::Constant::make_Int({ branch.first.end, ity })); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_gt), next_block, success_block }) ); - - m_builder.set_cur_block( success_block ); - this->generate_branch(branch.second, and_then); - - m_builder.set_cur_block( next_block ); - } - assert( m_builder.block_active() ); - - if( default_branch.is_Unset() ) { - // TODO: Emit error if non-exhaustive - m_builder.end_block( ::MIR::Terminator::make_Diverge({}) ); - } - else { - this->generate_branch(default_branch, and_then); - } -} - -void DecisionTreeGen::generate_branches_Unsigned( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Unsigned& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - auto ity = ty.m_data.as_Primitive(); - auto default_block = m_builder.new_bb_unlinked(); - - // TODO: Convert into an integer switch w/ offset instead of chained comparisons - - for( const auto& branch : branches ) - { - auto next_block = (&branch == &branches.back() ? default_block : m_builder.new_bb_unlinked()); - - auto cmp_gt_block = m_builder.new_bb_unlinked(); - auto val_cmp_lt = push_compare(sp, val.clone(), ::MIR::eBinOp::LT, ::MIR::Constant::make_Uint({ branch.first.start, ity })); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_lt), default_block, cmp_gt_block }) ); - m_builder.set_cur_block( cmp_gt_block ); - - auto success_block = m_builder.new_bb_unlinked(); - auto val_cmp_gt = push_compare(sp, val.clone(), ::MIR::eBinOp::GT, ::MIR::Constant::make_Uint({ branch.first.end, ity })); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_gt), next_block, success_block }) ); - - m_builder.set_cur_block( success_block ); - this->generate_branch(branch.second, and_then); - - m_builder.set_cur_block( next_block ); - } - assert( m_builder.block_active() ); - - if( default_branch.is_Unset() ) { - // TODO: Emit error if non-exhaustive - m_builder.end_block( ::MIR::Terminator::make_Diverge({}) ); - } - else { - this->generate_branch(default_branch, and_then); - } -} - -void DecisionTreeGen::generate_branches_Float( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Float& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - auto ity = ty.m_data.as_Primitive(); - auto default_block = m_builder.new_bb_unlinked(); - - for( const auto& branch : branches ) - { - auto next_block = (&branch == &branches.back() ? default_block : m_builder.new_bb_unlinked()); - - auto cmp_gt_block = m_builder.new_bb_unlinked(); - auto val_cmp_lt = push_compare(sp, val.clone(), ::MIR::eBinOp::LT, ::MIR::Constant::make_Float({ branch.first.start, ity })); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_lt), default_block, cmp_gt_block }) ); - m_builder.set_cur_block( cmp_gt_block ); - - auto success_block = m_builder.new_bb_unlinked(); - auto val_cmp_gt = push_compare(sp, val.clone(), ::MIR::eBinOp::GT, ::MIR::Constant::make_Float({ branch.first.end, ity })); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_gt), next_block, success_block }) ); - - m_builder.set_cur_block( success_block ); - this->generate_branch(branch.second, and_then); - - m_builder.set_cur_block( next_block ); - } - assert( m_builder.block_active() ); - - if( default_branch.is_Unset() ) { - ERROR(sp, E0000, "Match over floating point with no `_` arm"); - } - else { - this->generate_branch(default_branch, and_then); - } -} - -void DecisionTreeGen::generate_branches_Char( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Unsigned& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - auto default_block = m_builder.new_bb_unlinked(); - - // TODO: Convert into an integer switch w/ offset instead of chained comparisons - - for( const auto& branch : branches ) - { - auto next_block = (&branch == &branches.back() ? default_block : m_builder.new_bb_unlinked()); - - auto cmp_gt_block = m_builder.new_bb_unlinked(); - auto val_cmp_lt = push_compare(sp, val.clone(), ::MIR::eBinOp::LT, ::MIR::Constant::make_Uint({ branch.first.start, ::HIR::CoreType::Char })); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_lt), default_block, cmp_gt_block }) ); - m_builder.set_cur_block( cmp_gt_block ); - - auto success_block = m_builder.new_bb_unlinked(); - auto val_cmp_gt = push_compare(sp, val.clone(), ::MIR::eBinOp::GT, ::MIR::Constant::make_Uint({ branch.first.end, ::HIR::CoreType::Char })); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_gt), next_block, success_block }) ); - - m_builder.set_cur_block( success_block ); - this->generate_branch(branch.second, and_then); - - m_builder.set_cur_block( next_block ); - } - assert( m_builder.block_active() ); - - if( default_branch.is_Unset() ) { - // TODO: Error if not exhaustive. - m_builder.end_block( ::MIR::Terminator::make_Diverge({}) ); - } - else { - this->generate_branch(default_branch, and_then); - } -} -void DecisionTreeGen::generate_branches_Bool( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Bool& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - //assert( ty.m_data.is_Boolean() ); - - if( default_branch.is_Unset() ) - { - if( branches.false_branch.is_Unset() || branches.true_branch.is_Unset() ) { - // Non-exhaustive match - ERROR - } - } - else - { - if( branches.false_branch.is_Unset() && branches.true_branch.is_Unset() ) { - // Unreachable default (NOTE: Not an error here) - } - } - - // Emit an if based on the route taken - auto bb_false = m_builder.new_bb_unlinked(); - auto bb_true = m_builder.new_bb_unlinked(); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val), bb_true, bb_false }) ); - - // Recurse into sub-patterns - const auto& branch_false = ( !branches.false_branch.is_Unset() ? branches.false_branch : default_branch ); - const auto& branch_true = ( !branches. true_branch.is_Unset() ? branches. true_branch : default_branch ); - - m_builder.set_cur_block(bb_true ); - this->generate_branch(branch_true , and_then); - m_builder.set_cur_block(bb_false); - this->generate_branch(branch_false, and_then); -} - -void DecisionTreeGen::generate_branches_Borrow_str( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_String& branches, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - // TODO: Chained comparisons with ordering. - // - Would this just emit a eBinOp? That implies deep codegen support for strings. - // - rustc emits calls to PartialEq::eq for this and for slices. mrustc could use PartialOrd and fall back to PartialEq if unavaliable? - // > Requires crate access here! - A memcmp call is probably better, probably via a binop - // NOTE: The below implementation gets the final codegen to call memcmp on the strings by emitting eBinOp::{LT,GT} - - // - Remove the wrapping Deref (which must be there) - ASSERT_BUG(sp, val.is_Deref(), "Match over str without a deref - " << val); - auto tmp = mv$( *val.as_Deref().val ); - val = mv$(tmp); - - auto default_bb = m_builder.new_bb_unlinked(); - - // TODO: Binary search? Perfect-Hash-Function? - assert( !branches.empty() ); - for(const auto& branch : branches) - { - auto next_bb = (&branch == &branches.back() ? default_bb : m_builder.new_bb_unlinked()); - - auto cmp_gt_bb = m_builder.new_bb_unlinked(); - - auto lt_val = push_compare(sp, val.clone(), ::MIR::eBinOp::LT, ::MIR::Constant(branch.first) ); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(lt_val), default_bb, cmp_gt_bb }) ); - m_builder.set_cur_block(cmp_gt_bb); - - auto eq_bb = m_builder.new_bb_unlinked(); - auto gt_val = push_compare(sp, val.clone(), ::MIR::eBinOp::GT, ::MIR::Constant(branch.first) ); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(gt_val), next_bb, eq_bb }) ); - m_builder.set_cur_block(eq_bb); - - this->generate_branch(branch.second, and_then); - - m_builder.set_cur_block(next_bb); - } - this->generate_branch(default_branch, and_then); -} - -void DecisionTreeGen::generate_branches_Enum( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Variant& branches, - const field_path_t& field_path, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - const auto& enum_ref = *ty.m_data.as_Path().binding.as_Enum(); - const auto& enum_path = ty.m_data.as_Path().path.m_data.as_Generic(); - const auto& variants = enum_ref.m_variants; - auto variant_count = variants.size(); - bool has_any = ! default_branch.is_Unset(); - - if( branches.size() < variant_count && ! has_any ) { - ERROR(sp, E0000, "Non-exhaustive match over " << ty << " - " << branches.size() << " out of " << variant_count << " present"); - } - // DISABLED: Some complex matches don't directly use some defaults - //if( branches.size() == variant_count && has_any ) { - // ERROR(sp, E0000, "Unreachable _ arm - " << branches.size() << " variants in " << enum_path); - //} - - auto any_block = (has_any ? m_builder.new_bb_unlinked() : 0); - - // Emit a switch over the variant - ::std::vector< ::MIR::BasicBlockId> variant_blocks; - variant_blocks.reserve( variant_count ); - for( const auto& branch : branches ) - { - if( variant_blocks.size() != branch.first ) { - assert( variant_blocks.size() < branch.first ); - assert( has_any ); - variant_blocks.resize( branch.first, any_block ); - } - variant_blocks.push_back( m_builder.new_bb_unlinked() ); - } - if( variant_blocks.size() != variant_count ) - { - ASSERT_BUG(sp, variant_blocks.size() < variant_count, "Branch count (" << variant_blocks.size() << ") > variant count (" << variant_count << ") in match of " << ty); - ASSERT_BUG(sp, has_any, "Non-exhaustive match and no any arm"); - variant_blocks.resize( variant_count, any_block ); - } - bool any_arm_used = ::std::any_of( variant_blocks.begin(), variant_blocks.end(), [any_block](const auto& blk){ return blk == any_block; } ); - - m_builder.end_block( ::MIR::Terminator::make_Switch({ - val.clone(), variant_blocks // NOTE: Copies the list, so it can be used lower down - }) ); - - // Emit sub-patterns, looping over variants - for( const auto& branch : branches ) - { - auto bb = variant_blocks[branch.first]; - const auto& var = variants[branch.first]; - DEBUG(branch.first << " " << var.first << " = " << branch.second); - - auto var_lval = ::MIR::LValue::make_Downcast({ box$(val.clone()), branch.first }); - - ::HIR::TypeRef fake_ty; - - TU_MATCHA( (var.second), (e), - (Unit, - DEBUG("- Unit"); - ), - (Value, - DEBUG("- Value"); - ), - (Tuple, - // Make a fake tuple - ::std::vector< ::HIR::TypeRef> ents; - for( const auto& fld : e ) - { - ents.push_back( monomorphise_type(sp, enum_ref.m_params, enum_path.m_params, fld.ent) ); - } - fake_ty = ::HIR::TypeRef( mv$(ents) ); - m_builder.resolve().expand_associated_types(sp, fake_ty); - DEBUG("- Tuple - " << fake_ty); - ), - (Struct, - ::std::vector< ::HIR::TypeRef> ents; - for( const auto& fld : e ) - { - ents.push_back( monomorphise_type(sp, enum_ref.m_params, enum_path.m_params, fld.second.ent) ); - } - fake_ty = ::HIR::TypeRef( mv$(ents) ); - m_builder.resolve().expand_associated_types(sp, fake_ty); - DEBUG("- Struct - " << fake_ty); - ) - ) - - m_builder.set_cur_block( bb ); - if( fake_ty == ::HIR::TypeRef() || fake_ty.m_data.as_Tuple().size() == 0 ) { - this->generate_branch(branch.second, and_then); - } - else { - this->generate_branch(branch.second, [&](auto& subnode) { - // Call special handler to determine when the enum is over - this->generate_tree_code__enum(sp, subnode, fake_ty, var_lval, field_path, and_then); - }); - } - } - - if( any_arm_used ) - { - DEBUG("_ = " << default_branch); - if( !default_branch.is_Unset() ) - { - m_builder.set_cur_block(any_block); - this->generate_branch(default_branch, and_then); - } - } - else - { - DEBUG("_ = UNUSED - " << default_branch); - } -} - -void DecisionTreeGen::generate_branches_Slice( - const Span& sp, - const DecisionTreeNode::Branch& default_branch, - const DecisionTreeNode::Values::Data_Slice& branches, - const field_path_t& field_path, - const ::HIR::TypeRef& ty, ::MIR::LValue val, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - if( default_branch.is_Unset() ) { - ERROR(sp, E0000, "Non-exhaustive match over " << ty); - } - - auto val_len = m_builder.lvalue_or_temp(sp, ::HIR::CoreType::Usize, ::MIR::RValue::make_DstMeta({ m_builder.get_ptr_to_dst(sp, val).clone() })); - - // NOTE: Un-deref the slice - ASSERT_BUG(sp, val.is_Deref(), "slice matches must be passed a deref"); - auto tmp = mv$( *val.as_Deref().val ); - val = mv$(tmp); - - auto any_block = m_builder.new_bb_unlinked(); - - // TODO: Select one of three ways of picking the arm: - // - Integer switch (unimplemented) - // - Binary search - // - Sequential comparisons - - // TODO: Binary search instead? - for( const auto& branch : branches.fixed_arms ) - { - auto val_des = ::MIR::Constant::make_Uint({ static_cast<uint64_t>(branch.first), ::HIR::CoreType::Usize }); - - // Special case - final just does equality - if( &branch == &branches.fixed_arms.back() ) - { - auto val_cmp_eq = push_compare(sp, val_len.clone(), ::MIR::eBinOp::EQ, mv$(val_des)); - - auto success_block = m_builder.new_bb_unlinked(); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_eq), success_block, any_block }) ); - - m_builder.set_cur_block( success_block ); - this->generate_branch(branch.second, and_then); - - m_builder.set_cur_block( any_block ); - } - // Special case for zero (which can't have a LT) - else if( branch.first == 0 ) - { - auto next_block = m_builder.new_bb_unlinked(); - auto val_cmp_eq = push_compare(sp, val_len.clone(), ::MIR::eBinOp::EQ, mv$(val_des)); - - auto success_block = m_builder.new_bb_unlinked(); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_eq), success_block, next_block }) ); - - m_builder.set_cur_block( success_block ); - this->generate_branch(branch.second, and_then); - - m_builder.set_cur_block( next_block ); - } - // General case, with two comparisons - else - { - auto next_block = m_builder.new_bb_unlinked(); - - auto cmp_gt_block = m_builder.new_bb_unlinked(); - auto val_cmp_lt = push_compare(sp, val_len.clone(), ::MIR::eBinOp::LT, val_des.clone()); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_lt), any_block, cmp_gt_block }) ); - m_builder.set_cur_block( cmp_gt_block ); - - auto success_block = m_builder.new_bb_unlinked(); - auto val_cmp_gt = push_compare(sp, val_len.clone(), ::MIR::eBinOp::GT, mv$(val_des)); - m_builder.end_block( ::MIR::Terminator::make_If({ mv$(val_cmp_gt), next_block, success_block }) ); - - m_builder.set_cur_block( success_block ); - this->generate_branch(branch.second, and_then); - - m_builder.set_cur_block( next_block ); - } - } - assert( m_builder.block_active() ); - - if( default_branch.is_Unset() ) { - // TODO: Emit error if non-exhaustive - m_builder.end_block( ::MIR::Terminator::make_Diverge({}) ); - } - else { - this->generate_branch(default_branch, and_then); - } -} - -namespace { - bool path_starts_with(const field_path_t& test, const field_path_t& prefix) - { - //DEBUG("test="<<test<<", prefix="<<prefix); - if( test.size() < prefix.size() ) - { - return false; - } - else if( ! ::std::equal(prefix.data.begin(), prefix.data.end(), test.data.begin()) ) - { - return false; - } - else - { - return true; - } - } -} - -void DecisionTreeGen::generate_tree_code__enum( - const Span& sp, - const DecisionTreeNode& node, const ::HIR::TypeRef& fake_ty, const ::MIR::LValue& val, - const field_path_t& path_prefix, - ::std::function<void(const DecisionTreeNode&)> and_then - ) -{ - if( ! path_starts_with(node.m_field_path, path_prefix) ) - { - and_then(node); - } - else - { - this->generate_tree_code(sp, node, fake_ty, path_prefix.size(), val, - [&](const auto& next_node) { - if( ! path_starts_with(next_node.m_field_path, path_prefix) ) - { - and_then(next_node); - } - else - { - this->generate_tree_code__enum(sp, next_node, fake_ty, val, path_prefix, and_then); - } - }); - } -} - |