summaryrefslogtreecommitdiff
path: root/src/hir_conv/bind.cpp
blob: 8447daeec549e25f839eeffe9b9f5243b0a9e928 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
 * Set binding pointers in TypeRef and Pattern
 */
#include "main_bindings.hpp"
#include <hir/visitor.hpp>
#include <hir/expr.hpp>
#include <algorithm>    // std::find_if

#include <hir_typeck/static.hpp>

namespace {

    
    enum class Target {
        TypeItem,
        Struct,
        Enum,
        EnumVariant,
    };
    const void* get_type_pointer(const Span& sp, const ::HIR::Crate& crate, const ::HIR::SimplePath& path, Target t)
    {
        if( path.m_crate_name != "" ) {
            TODO(sp, "Handle extern crates");
        }
        
        const ::HIR::Module*    mod = &crate.m_root_module;
        for( unsigned int i = 0; i < path.m_components.size()-1; i ++ )
        {
            const auto& pc = path.m_components[i];
            auto it = mod->m_mod_items.find( pc );
            if( it == mod->m_mod_items.end() ) {
                BUG(sp, "Couldn't find component " << i << " of " << path);
            }
            
            // If second-last, and an enum variant is desired, return the pointer to the enum
            if( i+1 == path.m_components.size()-1 && t == Target::EnumVariant )
            {
                TU_IFLET(::HIR::TypeItem, it->second->ent, Enum, e2,
                    return &e2;
                )
                else {
                    ERROR(sp, E0000, "Expected an enum at the penultimate node of " << path << ", got a " << it->second->ent.tag_str());
                }
            }
            else {
                TU_MATCH_DEF( ::HIR::TypeItem, (it->second->ent), (e2),
                (
                    BUG(sp, "Node " << i << " of path " << path << " wasn't a module");
                    ),
                (Module,
                    mod = &e2;
                    )
                )
            }
        }

        const auto& pc = path.m_components.back();
        auto it = mod->m_mod_items.find( pc );
        if( it == mod->m_mod_items.end() ) {
            BUG(sp, "Couldn't find final component of " << path);
        }
        
        switch(t)
        {
        case Target::TypeItem:  return &it->second->ent;
        case Target::EnumVariant:   throw "";
        
        case Target::Struct:
            TU_IFLET(::HIR::TypeItem, it->second->ent, Struct, e2,
                return &e2;
            )
            else {
                ERROR(sp, E0000, "Expected a struct at " << path << ", got a " << it->second->ent.tag_str());
            }
            break;
        case Target::Enum:
            TU_IFLET(::HIR::TypeItem, it->second->ent, Enum, e2,
                return &e2;
            )
            else {
                ERROR(sp, E0000, "Expected a enum at " << path << ", got a " << it->second->ent.tag_str());
            }
            break;
        }
        throw "";
    }
    
    void fix_type_params(const Span& sp, const ::HIR::GenericParams& params_def, ::HIR::PathParams& params)
    {
        if( params.m_types.size() == 0 ) {
            params.m_types.resize( params_def.m_types.size() );
        }
        if( params.m_types.size() != params_def.m_types.size() ) {
            ERROR(sp, E0000, "Incorrect parameter count, expected " << params_def.m_types.size() << ", got " << params.m_types.size());
        }
    }
    
    const ::HIR::Struct& get_struct_ptr(const Span& sp, const ::HIR::Crate& crate, ::HIR::GenericPath& path) {
        const auto& str = *reinterpret_cast< const ::HIR::Struct*>( get_type_pointer(sp, crate, path.m_path, Target::Struct) );
        fix_type_params(sp, str.m_params,  path.m_params);
        return str;
    }
    ::std::pair< const ::HIR::Enum*, unsigned int> get_enum_ptr(const Span& sp, const ::HIR::Crate& crate, ::HIR::GenericPath& path) {
        const auto& enm = *reinterpret_cast< const ::HIR::Enum*>( get_type_pointer(sp, crate, path.m_path, Target::EnumVariant) );
        const auto& des_name = path.m_path.m_components.back();
        unsigned int idx = ::std::find_if( enm.m_variants.begin(), enm.m_variants.end(), [&](const auto& x) { return x.first == des_name; }) - enm.m_variants.begin();
        if( idx == enm.m_variants.size() ) {
            ERROR(sp, E0000, "Couldn't find enum variant " << path);
        }
        
        fix_type_params(sp, enm.m_params,  path.m_params);
        return ::std::make_pair( &enm, idx );
    }
    
    
    class Visitor:
        public ::HIR::Visitor
    {
        const ::HIR::Crate& m_crate;

    public:
        Visitor(const ::HIR::Crate& crate):
            m_crate(crate)
        {}
        
        void visit_trait_path(::HIR::TraitPath& p) override
        {
            static Span sp;
            p.m_trait_ptr = &m_crate.get_trait_by_path(sp, p.m_path.m_path);
            
            ::HIR::Visitor::visit_trait_path(p);
        }
        
        
        void visit_pattern_Value(const Span& sp, ::HIR::Pattern& pat, ::HIR::Pattern::Value& val)
        {
            bool allow_enum = pat.m_data.is_Value();
            
            TU_IFLET( ::HIR::Pattern::Value, val, Named, ve,
                TU_IFLET( ::HIR::Path::Data, ve.path.m_data, Generic, pe,
                    const ::HIR::Enum* enm = nullptr;
                    const ::HIR::Module*  mod = &m_crate.m_root_module;
                    const auto& path = pe.m_path;
                    for(unsigned int i = 0; i < path.m_components.size() - 1; i ++ )
                    {
                        const auto& pc = path.m_components[i];
                        auto it = mod->m_mod_items.find( pc );
                        if( it == mod->m_mod_items.end() ) {
                            BUG(sp, "Couldn't find component " << i << " of " << path);
                        }
                        
                        if( i == path.m_components.size() - 2 ) {
                            // Here it's allowed to be either a module, or an enum.
                            TU_IFLET( ::HIR::TypeItem, it->second->ent, Module, e2,
                                mod = &e2;
                            )
                            else TU_IFLET( ::HIR::TypeItem, it->second->ent, Enum, e2,
                                enm = &e2;
                            )
                            else {
                                BUG(sp, "Node " << i << " of path " << ve.path << " wasn't a module or enum");
                            }
                        }
                        else {
                            TU_IFLET( ::HIR::TypeItem, it->second->ent, Module, e2,
                                mod = &e2;
                            )
                            else {
                                BUG(sp, "Node " << i << " of path " << ve.path << " wasn't a module");
                            }
                        }
                    }
                    const auto& pc = path.m_components.back();
                    if( enm ) {
                        if( !allow_enum ) {
                            ERROR(sp, E0000, "Enum variant in range pattern - " << pat);
                        }
                        
                        // Enum variant
                        auto it = ::std::find_if( enm->m_variants.begin(), enm->m_variants.end(), [&](const auto&v){ return v.first == pc; });
                        if( it == enm->m_variants.end() ) {
                            BUG(sp, "'" << pc << "' isn't a variant in path " << path);
                        }
                        unsigned int index = it - enm->m_variants.begin();
                        auto path = mv$(pe);
                        fix_type_params(sp, enm->m_params,  path.m_params);
                        //::std::cout << "HHHH: path=" << path << ::std::endl;
                        pat.m_data = ::HIR::Pattern::Data::make_EnumValue({
                            mv$(path),
                            enm,
                            index
                            });
                    }
                    else {
                        auto it = mod->m_value_items.find( pc );
                        if( it == mod->m_value_items.end() ) {
                            BUG(sp, "Couldn't find final component of " << path);
                        }
                        // Unit-like struct match or a constant
                        TU_MATCH_DEF( ::HIR::ValueItem, (it->second->ent), (e2),
                        (
                            ERROR(sp, E0000, "Value pattern pointing to unexpected type")
                            ),
                        (Constant,
                            // TODO: Store reference to this item for later use
                            ),
                        (StructConstant,
                            // TODO: Convert into a dedicated pattern type
                            )
                        )
                    }
                )
                else {
                    // UFCS/Opaque, leave for now.
                }
            )
        }
        
        
        void visit_pattern(::HIR::Pattern& pat) override
        {
            static Span _sp = Span();
            const Span& sp = _sp;

            ::HIR::Visitor::visit_pattern(pat);
            
            TU_MATCH_DEF(::HIR::Pattern::Data, (pat.m_data), (e),
            (
                ),
            (Value,
                this->visit_pattern_Value(sp, pat, e.val);
                ),
            (Range,
                this->visit_pattern_Value(sp, pat, e.start);
                this->visit_pattern_Value(sp, pat, e.end);
                ),
            (StructTuple,
                const auto& str = get_struct_ptr(sp, m_crate, e.path);
                TU_IFLET(::HIR::Struct::Data, str.m_data, Tuple, _,
                    e.binding = &str;
                )
                else {
                    ERROR(sp, E0000, "Struct tuple pattern on non-tuple struct " << e.path);
                }
                ),
            (StructTupleWildcard,
                const auto& str = get_struct_ptr(sp, m_crate, e.path);
                TU_IFLET(::HIR::Struct::Data, str.m_data, Tuple, _,
                    e.binding = &str;
                )
                else {
                    ERROR(sp, E0000, "Struct tuple pattern on non-tuple struct " << e.path);
                }
                ),
            (Struct,
                const auto& str = get_struct_ptr(sp, m_crate, e.path);
                TU_IFLET(::HIR::Struct::Data, str.m_data, Named, _,
                    e.binding = &str;
                )
                else {
                    ERROR(sp, E0000, "Struct pattern on field-less struct " << e.path);
                }
                ),
            (EnumTuple,
                auto p = get_enum_ptr(sp, m_crate, e.path);
                const auto& var = p.first->m_variants[p.second].second;
                TU_IFLET(::HIR::Enum::Variant, var, Tuple, _,
                    e.binding_ptr = p.first;
                    e.binding_idx = p.second;
                )
                else {
                    ERROR(sp, E0000, "Enum tuple pattern on non-tuple variant " << e.path);
                }
                ),
            (EnumTupleWildcard,
                auto p = get_enum_ptr(sp, m_crate, e.path);
                const auto& var = p.first->m_variants[p.second].second;
                TU_IFLET(::HIR::Enum::Variant, var, Tuple, _,
                    e.binding_ptr = p.first;
                    e.binding_idx = p.second;
                )
                else {
                    ERROR(sp, E0000, "Enum tuple pattern on non-tuple variant " << e.path);
                }
                ),
            (EnumStruct,
                auto p = get_enum_ptr(sp, m_crate, e.path);
                const auto& var = p.first->m_variants[p.second].second;
                TU_IFLET(::HIR::Enum::Variant, var, Struct, _,
                    // All good
                    e.binding_ptr = p.first;
                    e.binding_idx = p.second;
                )
                else {
                    ERROR(sp, E0000, "Enum tuple pattern on non-tuple variant " << e.path);
                }
                )
            )
        }
        static void fix_param_count(const Span& sp, const ::HIR::GenericPath& path, const ::HIR::GenericParams& param_defs,  ::HIR::PathParams& params) {
            if( params.m_types.size() == param_defs.m_types.size() ) {
                // Nothing to do, all good
                return ;
            }
            
            if( params.m_types.size() == 0 ) {
                for(const auto& typ : param_defs.m_types) {
                    (void)typ;
                    params.m_types.push_back( ::HIR::TypeRef() );
                }
            }
            else if( params.m_types.size() > param_defs.m_types.size() ) {
                ERROR(sp, E0000, "Too many type parameters passed to " << path);
            }
            else {
                while( params.m_types.size() < param_defs.m_types.size() ) {
                    const auto& typ = param_defs.m_types[params.m_types.size()];
                    if( typ.m_default.m_data.is_Infer() ) {
                        ERROR(sp, E0000, "Omitted type parameter with no default in " << path);
                    }
                    else {
                        // TODO: What if this contains a generic param? (is that valid? Self maybe, what about others?)
                        params.m_types.push_back( typ.m_default.clone() );
                    }
                }
            }
        }
        void visit_type(::HIR::TypeRef& ty) override
        {
            static Span _sp = Span();
            const Span& sp = _sp;

            ::HIR::Visitor::visit_type(ty);
            
            TU_IFLET(::HIR::TypeRef::Data, ty.m_data, Path, e,
                TU_MATCH( ::HIR::Path::Data, (e.path.m_data), (pe),
                (Generic,
                    const auto& item = *reinterpret_cast< const ::HIR::TypeItem*>( get_type_pointer(sp, m_crate, pe.m_path, Target::TypeItem) );
                    TU_MATCH_DEF( ::HIR::TypeItem, (item), (e3),
                    (
                        ERROR(sp, E0000, "Unexpected item type returned for " << pe.m_path << " - " << item.tag_str());
                        ),
                    (Struct,
                        fix_param_count(sp, pe, e3.m_params,  pe.m_params);
                        e.binding = ::HIR::TypeRef::TypePathBinding::make_Struct(&e3);
                        ),
                    (Enum,
                        fix_param_count(sp, pe, e3.m_params,  pe.m_params);
                        e.binding = ::HIR::TypeRef::TypePathBinding::make_Enum(&e3);
                        ),
                    (Trait,
                        ty.m_data = ::HIR::TypeRef::Data::make_TraitObject({ ::HIR::TraitPath { mv$(pe), {}, {} }, {}, {} });
                        )
                    )
                    ),
                (UfcsUnknown,
                    //TODO(sp, "Should UfcsKnown be encountered here?");
                    ),
                (UfcsInherent,
                    ),
                (UfcsKnown,
                    if( pe.type->m_data.is_Path() && pe.type->m_data.as_Path().binding.is_Opaque() ) {
                        // - Opaque type, opaque result
                        e.binding = ::HIR::TypeRef::TypePathBinding::make_Opaque({});
                    }
                    else if( pe.type->m_data.is_Generic() ) {
                        // - Generic type, opaque resut. (TODO: Sometimes these are known - via generic bounds)
                        e.binding = ::HIR::TypeRef::TypePathBinding::make_Opaque({});
                    }
                    else {
                        //bool found = find_impl(sp, m_crate, pe.trait.m_path, pe.trait.m_params, *pe.type, [&](const auto& impl_params, const auto& impl) {
                        //    DEBUG("TODO");
                        //    return false;
                        //    });
                        //if( found ) {
                        //}
                        //TODO(sp, "Resolve known UfcsKnown - " << ty);
                    }
                    )
                )
            )
        }
        
        void visit_expr(::HIR::ExprPtr& expr) override
        {
            struct ExprVisitor:
                public ::HIR::ExprVisitorDef
            {
                Visitor& upper_visitor;
                
                ExprVisitor(Visitor& uv):
                    upper_visitor(uv)
                {}
                
                void visit(::HIR::ExprNode_Let& node) override
                {
                    upper_visitor.visit_type(node.m_type);
                    upper_visitor.visit_pattern(node.m_pattern);
                    ::HIR::ExprVisitorDef::visit(node);
                }
                void visit(::HIR::ExprNode_Match& node) override
                {
                    for(auto& arm : node.m_arms)
                    {
                        for(auto& pat : arm.m_patterns)
                            upper_visitor.visit_pattern(pat);
                    }
                    ::HIR::ExprVisitorDef::visit(node);
                }
                void visit(::HIR::ExprNode_Cast& node) override
                {
                    upper_visitor.visit_type(node.m_res_type);
                    ::HIR::ExprVisitorDef::visit(node);
                }
                
                void visit(::HIR::ExprNode_CallPath& node) override
                {
                    upper_visitor.visit_path(node.m_path, ::HIR::Visitor::PathContext::VALUE);
                    ::HIR::ExprVisitorDef::visit(node);
                }
                void visit(::HIR::ExprNode_CallMethod& node) override
                {
                    upper_visitor.visit_path_params(node.m_params);
                    ::HIR::ExprVisitorDef::visit(node);
                }
                
                void visit(::HIR::ExprNode_Closure& node) override
                {
                    upper_visitor.visit_type(node.m_return);
                    for(auto& arg : node.m_args) {
                        upper_visitor.visit_pattern(arg.first);
                        upper_visitor.visit_type(arg.second);
                    }
                    ::HIR::ExprVisitorDef::visit(node);
                }
            };
            
            if( expr.get() != nullptr )
            {
                ExprVisitor v { *this };
                (*expr).visit(v);
            }
        }
    };
}

void ConvertHIR_Bind(::HIR::Crate& crate)
{
    Visitor exp { crate };
    exp.visit_crate( crate );
}