summaryrefslogtreecommitdiff
path: root/tiger-compiler/src/object/type-checker.cc
blob: 76c4e8826654ef8af39642bc66fdf94d34f8f748 (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
/**
 ** \file object/type-checker.cc
 ** \brief Implementation for object/type-checker.hh.
 */

#include <iostream>
#include <memory>
#include <sstream>
#include <boost/iterator/zip_iterator.hpp>

#include <ast/all.hh>
#include <object/type-checker.hh>
#include <type/types.hh>

namespace object
{
  TypeChecker::TypeChecker()
    : super_type()
  {
    // Reset the subclasses of Object.  This is required if several
    // trees are processed during the compilation.
    type::Class::object_instance().subclasses_clear();

    // `self' variables are the only valid variables having a null
    // declaration site.  Use this property to tag them as read-only.
    // FIXME DONE: Some code was deleted here.
    var_read_only_.insert(nullptr);
  }

  /*--------------------------.
  | The core of the visitor.  |
  `--------------------------*/

  /*-----------------.
  | Visiting /Var/.  |
  `-----------------*/

  void TypeChecker::operator()(ast::SimpleVar& e)
  {
    // FIXME DONE: Some code was deleted here.
    if (e.name_get() == "self")
      type_default(e, current_);
    else
      super_type::operator()(e);
  }

  void TypeChecker::operator()(ast::FieldVar& e)
  {
    const type::Type* def_type = nullptr;
    // FIXME DONE: Some code was deleted here (Grab type).
    def_type = type(e.var_get());
    auto class_type = dynamic_cast<const type::Class*>(&def_type->actual());

    if (class_type)
      {
        // FIXME DONE: Some code was deleted here.
        auto attr = class_type->attr_find(e.name_get());
        if (attr == nullptr)
          error(e, "No such attribute found");
        else
          type_default(e, attr->def_get()->type_get());
      }
    else
      super_type::operator()(e);
  }

  /*----------------.
  | Visiting /Ty/.  |
  `----------------*/

  // Handle the case of `Object'.
  void TypeChecker::operator()(ast::NameTy& e)
  {
    // FIXME DONE: Some code was deleted here.
    if (e.name_get() == "Object")
      {
        type_default(e, &type::Class::object_instance());
      }
    else
      super_type::operator()(e);
  }

  /*-----------------.
  | Visiting /Exp/.  |
  `-----------------*/

  void TypeChecker::operator()(ast::IfExp& e)
  {
    // We want to handle the following case
    // let
    //   class A {}
    //   class B extends A { method print() = () }
    //   var a :=
    //     if 1 then
    //       new B
    //     else
    //       new A
    // in
    //    a.print() /* error */
    // end
    // FIXME DONE: Some code was deleted here.
    //Martial: Pré typage
    super_type::operator()(e);
    //Martial: Check mentionné au-dessus
    if (auto then_class = dynamic_cast<type::Class*>(&e.thenclause_get());
        then_class)
      {
        auto else_class = dynamic_cast<type::Class*>(&e.elseclause_get());
        if (then_class->id_get() != else_class->id_get())
          type_mismatch(e, "then clause", *e.thenclause_get().type_get(),
                        "else clause", *e.elseclause_get().type_get());
      }
  }

  void TypeChecker::operator()(ast::OpExp& e)
  {
    // We want to only compare equal static object types.
    // Otherwise, the desugarer emits wrong code on:
    //
    // let
    //   class A {}
    //   class B extends A {}
    //   var a := new A
    //   var b := new B
    // in
    //   a = b
    // end
    // FIXME DONE: Some code was deleted here.
    //Martial: Pré typage
    super_type::operator()(e);
    //Martial: Check mentionné au-dessus

    const ast::OpExp::Oper operation_type = e.oper_get();
    const auto a_class =
      dynamic_cast<const type::Class*>(&e.left_get().type_get()->actual());
    const auto b_class =
      dynamic_cast<const type::Class*>(&e.right_get().type_get()->actual());

    if (!a_class || !b_class || operation_type < ast::OpExp::Oper::eq
        || operation_type > ast::OpExp::Oper::ne)
      {
        return;
      }

    if (a_class->id_get() != b_class->id_get())
      {
        type_mismatch(e, "left operand", *e.left_get().type_get(),
                      "right operand", *e.right_get().type_get());
      }
  }

  void TypeChecker::operator()(ast::ObjectExp& e)
  {
    // FIXME DONE: Some code was deleted here.
    type(e.type_name_get());
    type_default(e, e.type_name_get().type_get());
  }

  void TypeChecker::operator()(ast::MethodCallExp& e)
  {
    // FIXME DONE: Some code was deleted here.
    type(e.object_get());
    for (ast::Exp* exp : e.args_get())
      {
        type(*exp);
      }
    const auto actual_params = e.args_get();

    const auto obj =
      dynamic_cast<const type::Class*>(&e.object_get().type_get()->actual());
    assertion(obj != nullptr);
    const auto meth = obj->meth_find(e.name_get());

    if (!meth)
      {
        // std::string error_message = "method ";
        error(e,
              "method " + e.name_get().get()
                + " does not exist within the "
                  "class");
        type_default(e, &default_type);
        return;
      }

    e.def_set(const_cast<ast::MethodDec*>(meth->def_get()));
    const auto expected_params = e.def_get()->formals_get().decs_get();

    if (actual_params.size() != expected_params.size())
      {
        error(e,
              std::string(std::to_string(expected_params.size())
                          + " parameters expected but got "
                          + std::to_string(actual_params.size())));
      }
    else
      {
        std::for_each(
          boost::make_zip_iterator(
            boost::make_tuple(expected_params.begin(), actual_params.begin())),
          boost::make_zip_iterator(
            boost::make_tuple(expected_params.end(), actual_params.end())),
          [this, &e](const boost::tuple<ast::VarDec*, ast::Exp*>& params) {
            check_types(e, "expected", *params.get<0>(), "actual",
                        *params.get<1>());
          });
      }

    type_default(e,
                 &dynamic_cast<const type::Method*>(e.def_get()->type_get())
                    ->result_get());
  }

  /*-----------------.
  | Visiting /Dec/.  |
  `-----------------*/

  /*--------------------.
  | Visiting TypeChunk. |
  `--------------------*/

  void TypeChecker::operator()(ast::TypeChunk& e)
  {
    // Visit the header and the body of the typechunk, as in
    // type::TypeChecker.
    super_type::operator()(e);

    // However, class members are not considered part of the body of
    // their class here; they are processed separately to allow valid
    // uses of the class from its members.
    for (ast::TypeDec* typedec : e)
      {
        ast::Ty& ty = typedec->ty_get();
        if (auto classty = dynamic_cast<ast::ClassTy*>(&ty))
          visit_dec_members(*classty);
      }
  }

  /*----------------------.
  | Visiting MethodChunk. |
  `----------------------*/

  void TypeChecker::operator()(ast::MethodChunk& e)
  {
    precondition(within_class_body_p_);
    within_class_body_p_ = false;

    // Two passes: once on headers, then on bodies.
    for (ast::MethodDec* m : e)
      visit_dec_header(*m);
    for (ast::MethodDec* m : e)
      visit_dec_body(*m);

    within_class_body_p_ = true;
  }

  // Store the type of this method.
  void TypeChecker::visit_dec_header(ast::MethodDec& e)
  {
    assertion(current_);

    // FIXME DONE: Some code was deleted here.
    const type::Record* formals = type(e.formals_get());

    const type::Type* return_type = e.result_get() != nullptr
      ? type(*e.result_get())
      : &type::Void::instance();

    auto type =
      std::make_unique<type::Method>(e.name_get(), current_, formals, *return_type, &e);

    // Check for multiple definitions in the current class.
    for (const type::Method* m : current_->meths_get())
      if (m->name_get() == e.name_get())
        return error(e, "method multiply defined", e.name_get());

    // Check for signature conformance w.r.t. super class, if applicable.
    const auto* super_meth_type =
      dynamic_cast<const type::Method*>(current_->meth_type(e.name_get()));
    // FIXME DONE: Some code was deleted here.
    if (super_meth_type && !super_meth_type->compatible_with(*type.get()))
      type_mismatch(e, "super class method signature", *super_meth_type,
                    "child class method signature", *type.get());
    else
      type_default(e, type.get());
    current_->meth_add(type.release());
  }

  // Type check this method's body.
  void TypeChecker::visit_dec_body(ast::MethodDec& e)
  {
    visit_routine_body<type::Method>(e);
  }

  /*---------------.
  | Visit VarDec.  |
  `---------------*/

  void TypeChecker::operator()(ast::VarDec& e)
  {
    // Signal that we are not directly inside a class' body, to avoid binding
    // spurious members.
    //
    // For example:
    // let
    //   class A =
    //   {
    //     var a := let var b := 0 in b end
    //   }
    //   var toto := new A
    // in
    //   toto.a /* Valid */
    //   toto.b /* Invalid */
    // end
    bool saved_within_class_body = within_class_body_p_;
    within_class_body_p_ = false;
    super_type::operator()(e);
    within_class_body_p_ = saved_within_class_body;

    /* If we are directly inside a class declaration then E is an attribute:
       record it into the CURRENT_ class.  */
    if (within_class_body_p_)
      {
        assertion(current_);

        if (current_->attr_type(e.name_get()))
          error(e, "attribute multiply defined", e.name_get());
        else
          current_->attr_add(&e);
      }
  }

  /*-------------.
  | Visit /Ty/.  |
  `-------------*/

  // Don't handle members, as visit_dec_members is in charge of this task.
  void TypeChecker::operator()(ast::ClassTy& e)
  {
    // FIXME DONE: Some code was deleted here (Create class).
    /*
    ** Moi sur le point de me faire chier dessus en code review parce que ma
    ** variable est en français juste pour éviter le keyword `class'
    */
    auto classe = std::make_unique<type::Class>();

    type_default(e, classe.get());

    /* ------------------- *
     * Superclass handling *
     * ------------------- */

    // FIXME DONE: Some code was deleted here (Set the type of the super class).

    const type::Type* supertype;
    if (e.super_get().def_get() == nullptr)
      supertype = type(e.super_get());
    else
      supertype = type(e.super_get().def_get()->ty_get());

    classe->super_set(dynamic_cast<const type::Class*>(&supertype->actual()));

    // FIXME DONE: Some code was deleted here (Recursively update the list of subclasses of the super classes).
    if (!classe->sound())
      error(e, "infinite type inheritance recursion detected");

    std::vector<const type::Class*> previous;
    for (auto super = classe->super_get(); super != nullptr
         && std::ranges::find(previous, super) == previous.end();
         super = super->super_get())
      {
        super->subclass_add(classe.get());
        previous.push_back(super);
      }

    /* à un moment je crois qu'il faut */
    created_type_default(e, classe.release());
    /* mais ça serait trop simple si je savais quand */
  }

  // Handle the members of a class.
  void TypeChecker::visit_dec_members(ast::ClassTy& e)
  {
    assertion(!within_class_body_p_); // Should be false by the time we get here
    const type::Type* type = nullptr;
    // FIXME DONE: Some code was deleted here.
    // là je crois faut get un type
    type = e.type_get();

    assertion(type);
    auto class_type = dynamic_cast<const type::Class*>(type);
    assertion(class_type);

    type::Class* saved_class_type = current_;
    within_class_body_p_ = true;
    // Make the type writable, so that we can add references to the
    // types of the members.
    current_ = const_cast<type::Class*>(class_type);
    e.chunks_get().accept(*this);

    // Set back the status we had before we visited the members.
    current_ = saved_class_type;
    within_class_body_p_ = false;
  }

} // namespace object