joshradin / Jodin-Java

An Object Oriented Extension to the C Language
0 stars 1 forks source link

Traits and Abstract Classes #18

Open joshradin opened 4 years ago

joshradin commented 4 years ago

Traits would allow for unrelated types to share similar function patterns, and share the same type declaration. This allows for completely unrelated types to passed through functions. An type declaration with implements a trait must implement all of its methods, unless its an abstract type.

Abstract classes would be able to declare certain methods abstract, meaning that they don't have to implement them. If an abstract classes implements a trait, it doesn't need to implement all of the functions.

Traits

For analysis, compiler will enforce that all implementing types define the functions. Will also enforce that trait objects can't be instantiated using the new operator.

Traits can be defined using this syntax:

trait NAME ( : TRAIT1, TRAIT2, ... TRAITn) {
   returnType methodName1(args...);
   returnType methodName2(args...);
   .
   .
   .
}

Traits can inherit other traits, which forces types implementing a trait to implement all of the other traits as well. Methods are forced to be public.

C - Implementation

Additional vtable struct for the trait, with an offset value for where the original position is.

struct TRAIT {
    i64 offset;
    function definitions...
}

When an object is casted to a trait object, it actually passes a pointer to the vtable. The calling pattern for a trait object is as follow: o->method->((void*) (o - o->offset), args...) or for an object with implements a trait: `o->TRAIT->method((void*) o, args...).

Interpreter - Implementation

Add to dynamic lookup table, compiler

Abstract Classes

Same as normal classes, but allow for abstract method declarations. Implementation would be simple. Make sure all non-abstract implementing classes implement all methods in compile time. No instantiations allowed using the new operator. Abstract classes are declared using this syntax: abstract class Name { ... }. The grammar for abstract classes is the same as a class, but the abstract declaration is allowed as well.

C - Implementation

Abstract classes struct are the same, but any non-implemented method in the vtable or a trait are set to a nullptr.