ReviewOS

home-lang/home

Parser: enum methods (associated fns inside enum body)

#52
Closed glennmichael123 opened this 24 days ago · 0 comments
24 days ago

Problem

The parser rejects method declarations inside an enum body. Today this fails with error[EP0001]: Expected variant name:

pub const Language = enum(u8) {
    English,
    Spanish,
    French,
    German,
    // ... more variants
    Norwegian,

    pub fn get_code(self: Language) []const u8 {
        return switch (self) {
            .English => \"en\",
            .Spanish => \"es\",
            .French => \"fr\",
            // ...
        };
    }
}

The parser is in 'expecting next variant' mode and sees pub fn instead — bails. Today the only way around it is to define the function as a free top-level fn, which is uglier and forces the Self parameter to spell out the enum name.

Affected kernel files

  • kernel/src/iot/voice_languages.home:43 (pub fn get_code(self: Language) []const u8)
  • kernel/src/iot/ambient_sound.home:74 (pub fn get_name(self: SoundClass) []const u8)

Expected behavior

After the variant list (or interleaved with it, like Zig), accept member-function declarations using the same grammar as struct methods. Inside the method body, self: EnumName (or just self) refers to the receiver; method-call sugar (x.get_code()) should dispatch to it.

Notes

  • Struct methods already work (multiple existing kernel files use pub fn inside pub const Foo = struct { ... }). Extend the same machinery to enum bodies.
  • Variant declarations and method declarations may be interleaved; or methods can be required to follow all variants. Either is acceptable. The kernel today places methods strictly after the variants.

Implementation hint

Wherever the enum-body parser distinguishes the next item, extend it to accept pub fn / fn / pub const (associated constants) similar to struct-body parsing. The two parsers likely share a lot of structure already — refactor so they share the inner-decl loop if cheap.

Tests

  • Positive: enum with methods, method called via dot-syntax
  • Positive: enum with associated pub const
  • Regression: enum with no methods, just variants

Acceptance

  1. The 2 listed kernel files clear home-debug ast past the method-decl point.
  2. Method-call dispatch through enum receiver works at typecheck time.
  3. Existing test suite green.

Sign in to comment on this issue.