TDA283-compiler-construction / project

Material for TDA283 / DIT300 Compiler Construction
11 stars 27 forks source link

Some missing tests for subtyping relation #20

Closed agustinmista closed 1 year ago

agustinmista commented 3 years ago

Hi!

I noticed that the OOP test suite is missing some tests to check that the subtyping relation is working correctly. In particular, generating valid LLVM code that allows more specific object arguments to be used by functions expecting more generic ones requires a ton of bitcast operations to be carefully inserted before invoking functions and methods.

Here is a small example adapted from testsuite/extensions/objects1/linked.jl:

class Animal { double weight; }

class Dog extends Animal { boolean good; }
class Cat extends Animal { int age; }

class Node {
  Animal elem;
  Node next;

  void   setElem(Animal a) { elem = a; }
  void   setNext(Node n) { next = n; }
  Animal getElem() { return elem; }
  Node   getNext() { return next; }
}

class Stack {
  Node head;

  boolean isEmpty() { return head==(Node)null; }

  void push(Animal a) {
    Node newHead = new Node;
    newHead.setElem(a);
    newHead.setNext(head);
    head = newHead;
  }

  void pop() { head = head.getNext(); }
  Animal top() { return head.getElem(); }
}

void pushBigger(Stack s, Animal x, Animal y) {
  if (x.weight > y.weight) {
    s.push(x);
  } else {
    s.push(y);
  }
}

int main() {
  Stack s = new Stack;

  Dog d1 = new Dog;
  d1.weight = 10.0;

  Cat c1 = new Cat;
  c1.weight = 5.0;

  pushBigger(s, d1, c1);

  Dog d2 = new Dog;
  d2.weight = 8.0;

  s.push(d2);

  while (!s.isEmpty()) {
    Animal a = s.top();
    printDouble(a.weight);
    s.pop();
  }
  return 0;
}

At least in my implementation, it is important that both Cats and Dogs are properly bitcasted to Animals before calling both the global pushBigger as well as the method Stack.push. Otherwise LLVM complains about a definition/usage type mismatch.

I'd be happy to open a PR with this test case if you think this is an important corner case.

myreen commented 1 year ago

Ah, I had missed this was here. Yes, please if you could open a PR adding this. Please make the PR to the next-year branch.