corx


A statically typed, general-purpose programming language, crafted for simplicity and performance.

"Trust the programmer" - corx









module main;

import * from "std:io"; # import all (std:io:printn)

contract shape; # forward declaration

# visitor contract
contract visitor {
    void visit(shape @s); # pass value by reference (value at)
};

# shape contract
contract shape {
    void accept(visitor @v);
};

# circle implementing shape
struct circle {
    float radius = 10.0;
    string name = "Circle";
} shape;

circle : void accept(visitor @v) {
    v.visit(this);
}

# rectangle implementing shape
struct rectangle {
    float width = 20.0;
    float height = 15.0;
    string name = "Rectangle";
} shape;

rectangle : void accept(visitor @v) {
    v.visit(this);
}

# square inherits from rectangle
struct square : rectangle {
    float width = 20.0;
    float height = 20.0;
    string name = "Square";
};

# method override
square : void accept(visitor @v) {
    this.width = 10.0;
    this.height = 10.0;

    v.visit(this);
};

# draw_visitor implementing visitor
struct draw_visitor {
} visitor;

draw_visitor : void visit(shape @s) {
    printn("Drawing a " + s.name);
}

# main function
int main(void) {

    shape **shapes = new *shape[3];  # dynamically allocates an array of 3 pointers
    shapes[0] = new circle();        # allocates on the heap
    shapes[1] = new rectangle();
    shapes[2] = new square();

    draw_visitor dv;

    for (int i = 0; i < 3; i++) {
        shapes[i]->accept(dv);
    }

    # clean up
    for (int i = 0; i < 3; i++) {
        purge shapes[i];
    }

    purge shapes;

    return 0;
}