0 | -- SPDX-FileCopyrightText: 2021 The toml-idr developers
 1 | --
 2 | -- SPDX-License-Identifier: MPL-2.0
 3 |
 4 | module Language.TOML.Value
 5 |
 6 | import public Data.SortedMap
 7 | import Data.List
 8 | import Data.String
 9 |
10 | public export
11 | Key : Type
12 | Key = String
13 |
14 | mutual
15 |     public export
16 |     data Value
17 |         = VString String
18 |         | VInteger Integer
19 |         | VFloat Double
20 |         | VBoolean Bool
21 |         | VArray (List Value)
22 |         | VTable Table
23 |     
24 |     public export
25 |     Table : Type
26 |     Table = SortedMap Key Value
27 |
28 |
29 | export
30 | lookupNested : (key : List String) -> (table : Table) -> Maybe Value
31 | lookupNested [] table = Nothing
32 | lookupNested [x] table = lookup x table
33 | lookupNested (x :: xs) table = do
34 |     VTable t <- lookup x table
35 |         | _ => Nothing
36 |     lookupNested xs t
37 |
38 |
39 | public export
40 | Eq Value where
41 |     (VString x) == (VString y) = x == y
42 |     (VInteger x) == (VInteger y) = x == y
43 |     (VFloat x) == (VFloat y) = x == y
44 |     (VBoolean x) == (VBoolean y) = x == y
45 |     (VArray xs) == (VArray ys) = assert_total $ xs == ys
46 |     (VTable x) == (VTable y) = assert_total $ SortedMap.toList x == SortedMap.toList y
47 |     _ == _ = False
48 |
49 |     a /= b = not $ (assert_total (==)) a b
50 |
51 |
52 | public export
53 | Show Value where
54 |     show (VString x) = show x
55 |     show (VInteger x) = show x
56 |     show (VFloat x) = show x
57 |     show (VBoolean True) = "true"
58 |     show (VBoolean False) = "false"
59 |     show (VArray xs) = "["
60 |         ++ fastConcat (intersperse ", " $ map (assert_total show) xs)
61 |         ++ "]"
62 |     show (VTable x) =
63 |         let kvs = the (List (Key, Value)) $ toList x in
64 |         "{"
65 |         ++ fastConcat (intersperse ", " . flip map kvs $ \(k, v) =>
66 |                             show k ++ " = " ++ assert_total show v
67 |                         )
68 |         ++ "}"
69 |
70 | export
71 | [Raw] Show Value where
72 |     show (VString x) = "string \{show x}"
73 |     show (VInteger x) = "integer \{show x}"
74 |     show (VFloat x) = "float \{show x}"
75 |     show (VBoolean x) = if x then "bool true" else "bool false"
76 |     show (VArray xs) = "list [\{concat $ intersperse ", " $ map (assert_total show) xs}]"
77 |     show (VTable x) =
78 |         let kvs = SortedMap.toList x in
79 |             "{\{fastConcat (intersperse ", " . flip map kvs $ \(kv) =>
80 |                             show k ++ " = " ++ assert_total show v
81 |                         )}}"
82 |
83 |