{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Language.Fiddle.Ast.Internal.SyntaxTree ( -- Type Families NumberType, RegisterOffset, BitsOffset, QMd, NamedUnit (..), FieldSpan (..), QRegMetadata (..), QBitsMetadata (..), RegSz(..), -- Witness Types Witness (..), -- AST Types Name (..), Directive (..), DirectiveBody (..), DirectiveElement (..), DirectiveExpression (..), Directed (..), FiddleUnit (..), Identifier (..), Expression (..), ConstExpression (..), ImportStatement (..), ImportList (..), FiddleDecl (..), ObjTypeBody (..), ObjType (..), ObjTypeDecl (..), Modifier (..), ModifierKeyword (..), DeferredRegisterBody (..), BodyType (..), RegisterBody (..), RegisterBitsDecl (..), RegisterBitsTypeRef (..), AnonymousBitsType (..), BitType (..), EnumBody (..), EnumConstantDecl (..), PackageBody (..), -- Helper Functions regSzToBits, mapDirected, mapDirectedM, asDirected, undirected, trueValue, ) where import Control.Monad (forM_) import Data.Aeson (FromJSON (..), ToJSON (..)) import Data.Kind (Type) import Data.List.NonEmpty hiding (map) import Data.Text (Text) import Data.Type.Bool import Data.Type.Equality import Data.Typeable import Data.Word (Word32) import GHC.Generics import Language.Fiddle.Ast.Internal.Instances import Language.Fiddle.Ast.Internal.Kinds import Language.Fiddle.Ast.Internal.MetaTypes import Language.Fiddle.Ast.Internal.Stage import Language.Fiddle.Internal.UnitInterface import Language.Fiddle.Internal.UnitNumbers type QMd s t = When (s .>= Qualified) t data FieldSpan u where FieldSpan :: { offset :: N u, size :: N u } -> FieldSpan u deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) -- | Metadata about a register. data QRegMetadata (checkStage :: Bool) where QRegMetadata :: { -- | The span of the register. Only reified in the Check stage. regSpan :: When checkStage (FieldSpan Bytes), -- | Is this a reified "reserved" register? regIsPadding :: Bool, -- | Was this register unnamed? This implies that the register should not -- emit getters and setters. regIsUnnamed :: Bool, -- | Full path to the register. regFullPath :: QualifiedPath String } -> QRegMetadata checkStage deriving (Generic, ToJSON) deriving instance (FromJSON (When s (FieldSpan Bytes))) => FromJSON (QRegMetadata s) data RegSz = RegSz8 | RegSz16 | RegSz32 | RegSz64 deriving (Eq, Ord, Show, Enum, Generic, ToJSON, FromJSON) regSzToBits :: RegSz -> N Bits regSzToBits RegSz8 = 8 regSzToBits RegSz16 = 16 regSzToBits RegSz32 = 32 regSzToBits RegSz64 = 64 data QBitsMetadata (checkStage :: Bool) where QBitsMetadata :: { bitsSpan :: When checkStage (FieldSpan Bits), bitsFullPath :: QualifiedPath String } -> QBitsMetadata checkStage deriving (Generic, ToJSON) deriving instance (FromJSON (When s (FieldSpan Bits))) => FromJSON (QBitsMetadata s) type BitsOffset stage = RegisterOffset stage -- | Type used for the RegisterOffset type. This is populated in the check -- stage, which will attach the appropriate offset to the register. This helps -- backends so they don't have to recalculate this offset. type family RegisterOffset stage where RegisterOffset stage = If (stage .< Checked) () Word32 -- | The Type of number during each stage of compilation. When in the first stage, -- numbers are just strings like anything else. In later stages, numbers get -- parsed into actual integers. This makes it easier to process later. type family NumberType (u :: k) (a :: Stage) :: Type where NumberType u s = If (s .< Expanded) Text (N u) -- A Name is multiple identifiers separated by dots. It's the way of namespaces -- to different packages. data Name :: SynTree where Name :: NonEmpty (Identifier f a) -> a -> Name f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents a directive in the Fiddle language. A directive provides -- additional metadata or instructions that the compiler can use during -- code generation. Directives can be attached to many elements in the -- syntax tree. data Directive :: SynTree where Directive :: { -- | The body of the directive. directiveBody :: f (DirectiveBody f a), -- | Annotation for the directive. directiveAnnot :: a } -> Directive f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents the body of a directive, which consists of multiple elements. data DirectiveBody :: SynTree where DirectiveBody :: { -- | Elements of the directive. directiveElements :: [DirectiveElement f a], -- | Annotation for the directive body. directiveBodyAnnot :: a } -> DirectiveBody f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents an element in a directive. Can be either a key or a key-value -- pair. data DirectiveElement :: SynTree where -- | A simple directive element with a key. The mere presence of this key -- holds semantic value. DirectiveElementKey :: { -- | Optional backend target. directiveBackend :: Maybe (Identifier f a), -- | The key of the directive. directiveKey :: Identifier f a, -- | Annotation for the directive element. directiveKeyAnnot :: a } -> DirectiveElement f a -- | A more complex directive element with a key-value pair, optionally -- specifying a backend. DirectiveElementKeyValue :: { -- | Optional backend target. directiveBackend :: Maybe (Identifier f a), -- | The key of the directive. directiveKey :: Identifier f a, -- | The value of the directive. directiveValue :: DirectiveExpression f a, -- | Annotation for the key-value directive. directiveKeyValueAnnot :: a } -> DirectiveElement f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents expressions that can be used within a directive, either a -- string or a number. data DirectiveExpression f a where DirectiveString :: { -- | String value of the directive. directiveStringValue :: Text, -- | Annotation for the directive string. directiveStringAnnot :: a } -> DirectiveExpression f a DirectiveNumber :: { -- | Number value of the directive. directiveNumberValue :: Text, -- | Annotation for the directive number. directiveNumberAnnot :: a } -> DirectiveExpression f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | A type that wraps another syntax tree and applies a list of directives to -- it. data Directed t stage f a where Directed :: { -- | List of directives. directedDirectives :: [Directive f a], -- | The wrapped syntax tree. directedSubtree :: t stage f a, -- | Annotation for the directed subtree. directedAnnot :: a } -> Directed t stage f a deriving (Generic, Annotated, Alter, Typeable) instance (Typeable (Directed t stage), Walk (t stage)) => Walk (Directed t stage) where walk fn (Directed directives subtree _) s = do forM_ directives $ \d -> ( \case Continue s' -> walk fn d s' _ -> return () ) =<< fn d s ( \case Continue s' -> walk fn subtree s' _ -> return () ) =<< fn subtree s -- | Apply a function to the underlying subtree in a 'Directed' type. mapDirected :: (t s f a -> t' s' f a) -> Directed t s f a -> Directed t' s' f a mapDirected fn (Directed dr tfa a) = Directed dr (fn tfa) a -- | Apply a monadic function to the underlying subtree in a 'Directed' type. mapDirectedM :: (Monad m) => (t s f a -> m (t' s' f a)) -> Directed t s f a -> m (Directed t' s' f a) mapDirectedM fn (Directed dr tfa a) = Directed dr <$> fn tfa <*> pure a -- | Convert an annotated syntax tree element to a 'Directed' type with -- an empty directive list. asDirected :: (Annotated (t s)) => t s f a -> Directed t s f a asDirected tfa = Directed [] tfa (annot tfa) -- | Extract the underlying subtree from a 'Directed' type, discarding any -- directives. undirected :: Directed t s f a -> t s f a undirected (Directed _ tfa _) = tfa -- | The root of the parse tree, containing a list of top-level declarations. data FiddleUnit (stage :: Stage) (f :: Type -> Type) a where FiddleUnit :: { -- | The interface for this FiddleUnit. Early on, this is just () because -- not enough information is provided to determine the interface.. fiddleUnitInterface :: When (stage == Checked) UnitInterface, -- | List of declarations. fiddleDecls :: [Directed FiddleDecl stage f a], -- | Annotation for the 'FiddleUnit'. fiddleUnitAnnot :: a } -> FiddleUnit stage f a deriving (Generic, Annotated, Typeable, Alter, Walk) -- | Represents an identifier with an associated annotation. data Identifier f a = Identifier { -- | The name of the identifier. identifierName :: !Text, -- | Annotation for the identifier. identifierAnnot :: a } deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Const expressions are expressions which must be eventually calculated -- during compilation. This means all the data required to fully calculate the -- expression must exist at compile time. data ConstExpression u (s :: Stage) :: SynTree where ConstExpression :: { constExpression :: Variant (s .>= Qualified) (N u) (Expression u s f a), constExpressionAnnot :: a } -> ConstExpression u s f a deriving (Generic, Annotated, Alter, Typeable, Walk) trueValue :: (s .>= Qualified ~ True) => ConstExpression u s f a -> N u trueValue (ConstExpression {constExpression = (LeftV v)}) = v -- | Expressions used within Fiddle, including literals and variables. data Expression (u :: unit) (s :: Stage) :: SynTree where -- | A numeric literal, whose value is dependent on the compilation stage. LitNum :: { -- | The numeric value. litNumValue :: Variant (stage .< Expanded) Text (N u), -- | Annotation for the literal. litNumAnnot :: a } -> Expression u stage f a -- | A variable reference. Var :: { -- | The identifier of the variable. varIdentifier :: Name f a, -- | Annotation for the variable. varAnnot :: a } -> Expression u stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents an import statement in the Fiddle language. data ImportStatement stage f a where ImportStatement :: { -- | The path to import. importPath :: Text, -- | Optional list of imported items. importList :: Maybe (ImportList f a), importInterface :: When (stage .>= ImportsResolved) UnitInterface, -- | Annotation for the import statement. importStatementAnnot :: a } -> ImportStatement stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | A list of imported identifiers. data ImportList f a where ImportList :: { -- | The list of identifiers. importIdentifiers :: [Identifier f a], -- | Annotation for the import list. importListAnnot :: a } -> ImportList f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents top-level declarations in Fiddle. data FiddleDecl :: StagedSynTree where -- | An option declaration in the form 'option '. OptionDecl :: { -- | The key of the option. optionKey :: Identifier f a, -- | The value of the option. optionValue :: Identifier f a, -- | Annotation for the option declaration. optionAnnot :: a } -> FiddleDecl stage f a -- | An import declaration. ImportDecl :: { -- | The imported type. importStatement :: ImportStatement stage f a, -- \| Annotation for the import declaration. -- | The interface for this imported file. This type depends on the stage -- of compilation. Initially it's just '()', but will eventually be resolved -- into a 'UnitInterface'. importDeclAnnot :: a } -> FiddleDecl stage f a -- | A using declaration. UsingDecl :: { -- Using decls should be removed during qualification. disableUsingDeclAfterQualification :: Witness True, -- TODO change to < Qualified. -- | The name being used. usingName :: Name f a, -- | Annotation for the using declaration. usingAnnot :: a } -> FiddleDecl stage f a -- | A package declaration. PackageDecl :: { -- | Qualification metadata about this package statement. packageQualificationMetadata :: f (QMd stage ExportedPackageDecl), -- | The package name. packageName :: Name f a, -- | The body of the package. packageBody :: f (PackageBody stage f a), -- | Annotation for the package declaration. packageAnnot :: a } -> FiddleDecl stage f a -- | A location declaration in the form 'location = '. LocationDecl :: { -- | qualified metadata about this location. locationQualificationMetadata :: f (QMd stage ExportedLocationDecl), -- | The location identifier. locationIdent :: Identifier f a, -- | The associated expression. locationExpr :: ConstExpression Address stage f a, -- | Annotation for the location declaration. locationAnnot :: a } -> FiddleDecl stage f a -- | A bits declaration in the form 'bits : '. BitsDecl :: { -- | Qualification metadata about this "bits" declaration. bitsQualificationMetadata :: f (QMd stage ExportedBitsDecl), -- | The identifier of the bits. When initially parsed, this can only be -- an Identifier, but during compilation this may change to a "name". bitsName :: Name f a, -- | The type of the bits. bitsType :: BitType stage f a, -- | Annotation for the bits declaration. bitsAnnot :: a } -> FiddleDecl stage f a -- | An object type declaration. ObjTypeDecl :: { -- | Qualification metadata about this object type. objTypeQualificationMetadata :: f (QMd stage ExportedTypeDecl), -- | The identifier of the object type. objTypeIdent :: Name f a, -- | The body of the object type. objTypeBody :: f (ObjTypeBody stage f a), -- | Annotation for the object type declaration. objTypeAnnot :: a } -> FiddleDecl stage f a -- | An object declaration in the form 'object at : '. ObjectDecl :: { -- | Qualification metadata about this object. objectQualificationMetadata :: f (QMd stage ExportedObjectDecl), -- | The identifier of the object. objectIdent :: Identifier f a, -- | The location expression. objectLocation :: Expression Address stage f a, -- | The type of the object. objectType :: ObjType stage f a, -- | Annotation for the object declaration. objectAnnot :: a } -> FiddleDecl stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents the body of an object type, containing a body type (struct or -- union), a list of object declarations, and an annotation. data ObjTypeBody (stage :: Stage) (f :: Type -> Type) a where ObjTypeBody :: { -- | The body type (struct or union). objBodyType :: BodyType f a, -- | Object declarations. objBodyDecls :: [Directed ObjTypeDecl stage f a], -- | Annotation for the object type body. objBodyAnnot :: a } -> ObjTypeBody stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents an object type, which can be anonymous, an array, or a -- reference to another type. data ObjType stage f a where -- | An anonymous object type, allowed only in Parsed. AnonymousObjType :: { -- | Witness for stage constraint. disableAnonymousTypesAfterExpansion :: Witness (stage .< Expanded), -- | The body of the anonymous type. anonBody :: f (ObjTypeBody stage f a), -- | Annotation for the anonymous type. anonAnnot :: a } -> ObjType stage f a -- | An array of object types. ArrayObjType :: { -- | The type of the array elements. arrayObjType :: ObjType stage f a, -- | The size of the array. arraySize :: ConstExpression Unitless stage f a, -- | Annotation for the array type. arrayAnnot :: a } -> ObjType stage f a -- | A reference to an existing type by name. ReferencedObjType :: { refQualificationMetadata :: f (QMd stage ExportedTypeDecl), -- | The name of the referenced type. refName :: Name f a, -- | Annotation for the referenced type. refAnnot :: a } -> ObjType stage f a deriving (Typeable, Generic, Alter, Annotated, Typeable, Walk) -- | Represents a declaration inside an object type, such as a register, an -- assertion, or a substructure. data ObjTypeDecl stage f a where -- | An assertion statement for a specific position. AssertPosStatement :: { -- | Witness for stage constraint. disableAssertStatementsAfterConsistencyCheck :: Witness (stage .< Checked), -- | The expression for the assertion. assertExpr :: Expression Bytes stage f a, -- | Annotation for the assertion. assertAnnot :: a } -> ObjTypeDecl stage f a -- | A register declaration. RegisterDecl :: { -- | Offset within the register. Calculated during the consistency check. -- The offset is calculated from the top-level structure. qRegMeta :: When (stage .>= Qualified) (QRegMetadata (stage .>= Checked)), -- | Optional register modifier. regModifier :: Guaranteed (stage .>= Qualified) (Modifier f a), -- | Optional register identifier. This is guaranteed to exist after -- Qualification, where a generated identifier will be provided if it -- doesn't exist. regIdent :: Guaranteed (stage .>= Qualified) (Identifier f a), -- | Size of the register. regSize :: Variant (stage .>= Qualified) RegSz (Expression Bits stage f a), -- | Optional register body. regBody :: Maybe (RegisterBody stage f a), -- | Annotation for the register declaration. regAnnot :: a } -> ObjTypeDecl stage f a -- | A reserved declaration for padding or alignment. ReservedDecl :: { -- | Reserved "registers" should be reified in the qualification phase. noReservedAfterQualification :: Witness (stage .< Qualified), -- | The expression for reserved space. reservedExpr :: Expression Bits stage f a, -- | Annotation for the reserved declaration. reservedAnnot :: a } -> ObjTypeDecl stage f a -- | A declaration for a substructure (struct or union). TypeSubStructure :: { -- | The body of the substructure. subStructureBody :: f (ObjTypeBody stage f a), -- | Optional name for the substructure. subStructureName :: Maybe (Identifier f a), -- | Annotation for the substructure. subStructureAnnot :: a } -> ObjTypeDecl stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents a modifier for registers (e.g., read-only, read-write). data Modifier f a where ModifierKeyword :: { -- | The keyword for the modifier. modifierKey :: ModifierKeyword, -- | Annotation for the modifier. modifierAnnot :: a } -> Modifier f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Enumerates the different types of register modifiers. data ModifierKeyword = Rw | Ro | Wo | Pr deriving (Eq, Ord, Show, Read, Typeable) -- | Represents a deferred register body, consisting of a list of bit -- declarations. data DeferredRegisterBody stage f a where DeferredRegisterBody :: { deferredBits :: [Directed RegisterBitsDecl stage f a], -- | Annotation for the deferred register body. deferredAnnot :: a } -> DeferredRegisterBody stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents the body type (struct or union) in an object. data BodyType (f :: Type -> Type) a where Union :: { -- | Annotation for the union. unionAnnot :: a } -> BodyType f a Struct :: { -- | Annotation for the struct. structAnnot :: a } -> BodyType f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents a register body with a body type and deferred bit declarations. data RegisterBody stage f a where RegisterBody :: { -- | The body type of the register. regBodyType :: BodyType f a, -- | Deferred body. regDeferredBody :: f (DeferredRegisterBody stage f a), -- | Annotation for the register body. regBodyAnnot :: a } -> RegisterBody stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents declarations within a register, such as defined bits, -- reserved bits, or substructures. data RegisterBitsDecl stage f a where -- | Declaration for reserved bits. ReservedBits :: { -- | Expression for reserved bits. reservedBitsExpr :: Expression Bits stage f a, -- | Annotation for the reserved bits. reservedBitsAnnot :: a } -> RegisterBitsDecl stage f a -- | Declaration for defined bits in a register. DefinedBits :: { -- | The offset for these bits. This is calculated during the -- ConsistencyCheck phase, so until this phase it's just (). qBitsMetadata :: When (stage .>= Qualified) (QBitsMetadata (stage .>= Checked)), -- | Bit declarations. -- | Optional modifier for the bits. definedBitsModifier :: Guaranteed (stage .>= Qualified) (Modifier f a), -- | Identifier for the bits. definedBitsIdent :: Identifier f a, -- | Type reference for the bits. definedBitsTypeRef :: RegisterBitsTypeRef stage f a, -- | Annotation for the defined bits. definedBitsAnnot :: a } -> RegisterBitsDecl stage f a -- | Substructure within a register. BitsSubStructure :: { -- | The body of the substructure. bitsSubRegBody :: RegisterBody stage f a, -- | Optional name for the substructure. bitsSubName :: Maybe (Identifier f a), -- | Annotation for the substructure. bitsSubAnnot :: a } -> RegisterBitsDecl stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents different ways to refer to register bits, either as an array, -- a reference to a type, an anonymous type, or just bits. data RegisterBitsTypeRef stage f a where -- | An array of bits with a specified size. RegisterBitsArray :: { -- | Reference to the array type. bitsArrayTypeRef :: RegisterBitsTypeRef stage f a, -- | Size of the array. bitsArraySize :: ConstExpression Unitless stage f a, -- | Annotation for the array. bitsArrayAnnot :: a } -> RegisterBitsTypeRef stage f a -- | A reference to another type by name. RegisterBitsReference :: { -- | Qualification metadata about this Bits reference. bitsRefQualificationMetadata :: f (QMd stage ExportedBitsDecl), -- | The name of the referenced type. bitsRefName :: Name f a, -- | Annotation for the reference. bitsRefAnnot :: a } -> RegisterBitsTypeRef stage f a -- | An anonymous type for register bits, used in Parsed. RegisterBitsAnonymousType :: { -- | Witness for stage constraint. disableAnonymousBitsAfterExpansion :: Witness (stage .< Expanded), -- | The anonymous type. anonBitsType :: AnonymousBitsType stage f a, -- | Annotation for the anonymous type. anonBitsAnnot :: a } -> RegisterBitsTypeRef stage f a -- | A direct specification of bits as an expression. RegisterBitsJustBits :: { -- | Expression for the bits. justBitsExpr :: ConstExpression Bits stage f a, -- | Annotation for the bits. justBitsAnnot :: a } -> RegisterBitsTypeRef stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents an anonymous bit type, such as an enum, used in Parsed. data AnonymousBitsType stage f a where AnonymousEnumBody :: { -- | Expression defining the enum size. anonEnumSize :: Expression Bits stage f a, -- | The body of the enum. anonEnumBody :: f (EnumBody stage f a), -- | Annotation for the anonymous enum. anonEnumAnnot :: a } -> AnonymousBitsType stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents a bit type, either an enumeration or raw bits. data BitType (stage :: Stage) (f :: Type -> Type) a where -- | An enumeration type for bits. EnumBitType :: { -- | Expression defining the enum size. enumBitSize :: Expression Bits stage f a, -- | The body of the enum.set_stm32l4_gpio__bsr_r__set enumBitBody :: f (EnumBody stage f a), -- | Annotation for the enumeration. enumBitAnnot :: a } -> BitType stage f a -- | A raw bit type. RawBits :: { -- | Expression defining the bits. rawBitsExpr :: Expression Bits stage f a, -- | Annotation for the raw bits. rawBitsAnnot :: a } -> BitType stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents the body of an enumeration. data EnumBody (stage :: Stage) (f :: Type -> Type) a where EnumBody :: { -- | Enum constant declarations. enumConsts :: [Directed EnumConstantDecl stage f a], -- | Annotation for the enum body. enumBodyAnnot :: a } -> EnumBody stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents a declaration for an enumeration constant. data EnumConstantDecl stage f a where -- | A named constant in the enum. EnumConstantDecl :: { -- | Identifier for the constant. enumConstIdent :: Identifier f a, -- | Expression defining the constant. enumConstExpr :: ConstExpression Unitless stage f a, -- | Annotation for the constant. enumConstAnnot :: a } -> EnumConstantDecl stage f a -- | A reserved value in the enum. EnumConstantReserved :: { -- | Expression for the reserved value. enumReservedExpr :: Expression Unitless stage f a, -- | Annotation for the reserved value. enumReservedAnnot :: a } -> EnumConstantDecl stage f a deriving (Generic, Annotated, Alter, Typeable, Walk) -- | Represents the body of a package, containing a list of declarations. data PackageBody (stage :: Stage) (f :: Type -> Type) a where PackageBody :: { -- | Declarations in the package. packageBodyDecls :: [Directed FiddleDecl stage f a], -- | Annotation for the package body. packageBodyAnnot :: a } -> PackageBody stage f a deriving (Generic, Annotated, Typeable, Alter, Walk)