Paste: Factor Enumeration Ideas

Author: Leo Mehraban
Mode: factor
Date: Tue, 19 Aug 2025 15:39:23
Plain Text |
! ideas for how true enums in factor might be implemented

! enums are specified with the syntax:
! ENUMERATION: enum-name enum-val1 enum-val2 { enum-val3 5 } enum-val4 ;
! the arrays in the definition allow for custom specification of enum numbers, so enum-name.enum-val3 is 5, and
! enum-name.enum-val4 is 6

! the class name is used to namespace enums (enum elements are named class.name), but are also actual predicate classes
! that extend integer and check whether the input is within the array of numbers that have enum representations

! if this is turned into a full vocabulary (classes.enumerations or something), there would also be an implementation of the definition protocol for them, and probably also a section in the vocab word listing for enum elements, separating them from syntax words

: define-enum-elt ( class-name n name -- class-name n ) 
    over , "." prepend overd append create-word-in 
    [ over [ append ] curry ( parsed -- parsed ) define-declared ] keep t "parsing" set-word-prop 1 + ; 
    ! enum elements have the syntax class.elt, and they are parsing words so they work by default in case statements

: parse-enum ( class -- ) 
  [ 
    dup name>> 0 [
        scan-word-name 
        { 
            { ";" [ f ] } 
            { "{" 
                [
                    drop scan-word-name scan-number swap define-enum-elt scan-word-name drop t 
                ] 
            } 
            [ define-enum-elt t ] 
        } case 
    ] loop 2drop 
  ] { } make [ index ] curry integer swap define-predicate-class ;

SYNTAX: ENUMERATION: scan-new-class parse-enum ;

New Annotation

Summary:
Author:
Mode:
Body: