Skip to content

Support for "nocode" on enum declaration #70

Closed
@AaronFriel

Description

@AaronFriel

It would be very nice if c2hs supported a "nocode" version for enum, to support cases where the data declaration is not easily colocated with the enum instance, or they must be declared manually. One such use case: associated data types in data families. I imagine it would act as an additional alias rule that causes the data declaration not to be emitted, only instances. Example of how I imagine it would work with existing features below:

// foo.h

enum Foo {
  BAR,
  BAZ,
  QUX = 5,
  XYZZY_THUD
};
-- Flux.hs
module Flux where

class Flux a where
  data FluxCode a
  gigawattsNeeded :: Double
  gigawattsNeeded = 1.21
-- Foo.chs
module Foo where

import Flux

instance Flux Capacitor where
  -- associated data type decl
  data FluxCode Capacitor = Bar | Baz | Qux | Xyzzy

-- Note: must be able to define longer names here, I've used single quotes.
-- underscoreToCase still works, it aliases the C identifiers for the instance.
-- XYZZY_THUD is manually aliased.
-- nocode suppresses emitting a data declaration.
{# enum Foo as 'FluxCode Capacitor' {underscoreToCase, XYZZY_THUD as Xyzzy, nocode}
  deriving (Show Eq) #}
-- foo.hs (compiled from c2hs)
module Foo where

import Flux

instance Flux Capacitor where
  -- associated data type decl
  data FluxCode Capacitor = Bar | Baz | Qux | Xyzzy

instance Enum (FluxCode Capacitor) where
  fromEnum Foo = 0
  fromEnum Bar = 1
  fromEnum Baz = 2
  fromEnum Qux = 5
  fromEnum Xyzzy= 6

  toEnum 0 = Foo
  toEnum 1 = Bar
  toEnum 2 = Baz
  toEnum 5 = Qux
  toEnum 6 = Xyzzy
  toEnum unmatched = error ("FluxCode Capacitor.toEnum: Cannot match " ++ show unmatched)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions