1 -- | This module gathers utilities for parsing or viewing
2 -- infix, prefix and postfix combinators.
3 module Symantic.Semantics.Viewer.Fixity where
6 import Data.Eq (Eq (..))
7 import Data.Function ((.))
9 import Data.Maybe (Maybe (..))
10 import Data.Ord (Ord (..))
12 import Data.String (IsString (..), String)
13 import Text.Show (Show (..))
23 = Prefix {unifix_precedence :: Precedence}
24 | Postfix {unifix_precedence :: Precedence}
29 { infix_associativity :: Maybe Associativity
30 , infix_precedence :: Precedence
34 infixL :: Precedence -> Infix
35 infixL = Infix (Just AssocL)
37 infixR :: Precedence -> Infix
38 infixR = Infix (Just AssocR)
40 infixB :: Side -> Precedence -> Infix
41 infixB = Infix . Just . AssocB
43 infixN :: Precedence -> Infix
44 infixN = Infix Nothing
52 -- | Given 'Precedence' and 'Associativity' of its parent operator,
53 -- and the operand 'Side' it is in,
54 -- return whether an 'Infix' operator
55 -- needs to be enclosed by a 'Pair'.
56 isPairNeeded :: (Infix, Side) -> Infix -> Bool
57 isPairNeeded (po, lr) op =
58 infix_precedence op < infix_precedence po
59 || infix_precedence op == infix_precedence po
63 case (lr, infix_associativity po) of
64 (_, Just AssocB{}) -> True
65 (SideL, Just AssocL) -> True
66 (SideR, Just AssocR) -> True
69 -- | If 'isPairNeeded' is 'True',
70 -- enclose the given 'IsString' by given 'Pair',
71 -- otherwise returns the same 'IsString'.
80 pairIfNeeded (o, c) po op s =
82 then fromString o <> s <> fromString c
85 -- * Type 'Precedence'
88 -- ** Class 'PrecedenceOf'
89 class PrecedenceOf a where
90 precedence :: a -> Precedence
91 instance PrecedenceOf Fixity where
92 precedence (Fixity1 uni) = precedence uni
93 precedence (Fixity2 inf) = precedence inf
94 instance PrecedenceOf Unifix where
95 precedence = unifix_precedence
96 instance PrecedenceOf Infix where
97 precedence = infix_precedence
99 -- * Type 'Associativity'
101 = -- | Associate to the left: @a ¹ b ² c == (a ¹ b) ² c@
103 | -- | Associate to the right: @a ¹ b ² c == a ¹ (b ² c)@
105 | -- | Associate to both sides, but to 'Side' when reading.
118 type Pair = (String, String)
123 pairAngle = ("<", ">")
124 pairBrace = ("{", "}")
125 pairBracket = ("[", "]")
126 pairParen = ("(", ")")