1 module Language.Symantic.Grammar.Fixity where
3 import Data.Bool as Bool
5 import Data.String (IsString(..))
15 = Prefix { unifix_prece :: Precedence }
16 | Postfix { unifix_prece :: Precedence }
22 { infix_assoc :: Maybe Associativity
23 , infix_prece :: Precedence
26 infixL :: Precedence -> Infix
27 infixL = Infix (Just AssocL)
29 infixR :: Precedence -> Infix
30 infixR = Infix (Just AssocR)
32 infixB :: Side -> Precedence -> Infix
33 infixB = Infix . Just . AssocB
35 infixN :: Precedence -> Infix
36 infixN = Infix Nothing
44 -- | Given 'Precedence' and 'Associativity' of its parent operator,
45 -- and the operand 'Side' it is in,
46 -- return whether an 'Infix' operator
47 -- needs to be enclosed by parenthesis.
48 needsParenInfix :: (Infix, Side) -> Infix -> Bool
49 needsParenInfix (po, lr) op =
50 infix_prece op < infix_prece po
51 || infix_prece op == infix_prece po
55 case (lr, infix_assoc po) of
56 (_, Just AssocB{}) -> True
57 (SideL, Just AssocL) -> True
58 (SideR, Just AssocR) -> True
61 -- | If 'needsParenInfix' is 'True',
62 -- enclose the given 'IsString' by parenthesis,
63 -- otherwise returns the same 'IsString'.
65 :: (Semigroup s, IsString s)
66 => (Infix, Side) -> Infix -> s -> s
68 if needsParenInfix po op
69 then fromString "(" <> s <> fromString ")"
72 -- * Type 'Precedence'
75 -- ** Class 'PrecedenceOf'
76 class PrecedenceOf a where
77 precedence :: a -> Precedence
78 instance PrecedenceOf Fixity where
79 precedence (Fixity1 uni) = precedence uni
80 precedence (Fixity2 inf) = precedence inf
81 instance PrecedenceOf Unifix where
82 precedence = unifix_prece
83 instance PrecedenceOf Infix where
84 precedence = infix_prece
86 -- * Type 'Associativity'
88 = AssocL -- ^ Associate to the left: @a ¹ b ² c == (a ¹ b) ² c@
89 | AssocR -- ^ Associate to the right: @a ¹ b ² c == a ¹ (b ² c)@
90 | AssocB Side -- ^ Associate to both sides, but to 'Side' when reading.