LemLib / hardware

Hardware Abstractions for the Vex V5
MIT License
1 stars 1 forks source link

✨ Static Port Range Checks #6

Open SizzinSeal opened 2 days ago

SizzinSeal commented 2 days ago

Overview

User code should not compile if the user tries to pass a port to a sensor that's not valid

Example

lemlib::V5RotationSensor a(0); // this should not compile
lemlib::V5RotationSensor b(22); // this should not compile
ion098 commented 1 day ago

This is possible, and something I've tried to do in hopes of PRing it to PROS, but there's no way of doing it that doesn't risk breaking user code. Luckily, we don't have the issue of backwards compatibility. Here's a proof of concept:

struct DynamicPort {};

constexpr DynamicPort runtime_check_port{};

class Port {
    public:
    consteval Port(int64_t port): m_port(port) {
        // XXX: this doesnt actaully throw an exception since the ctor 
        // is consteval, it halts compilation instead
        if (port < 1 || port > 21) throw "Port out of range!";     
    }
    Port(int64_t port, DynamicPort) : m_port(port) {}
    private:
    uint8_t m_port;
};

class Device {
    public:
    Device(Port port): m_port(port) {}
    private:
    Port m_port;
};

int main() {
    Device motor(2);
    // this won't compile
    // Device invalid(22);
    int i = 22; // read from sd card perhaps
    // this won't compile
    // Device rotation(i);
    Device rotation(Port(i, runtime_check_port));
}