aboutsummaryrefslogtreecommitdiffstats
path: root/style-generator/src/Decoder.elm
blob: 65dc0a27551d40897c44aebbf4113cc89b7e9462 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
module Decoder exposing (styleCode)

import Color
import Elm.Syntax.Declaration exposing (Declaration(..))
import Elm.Syntax.Exposing exposing (Exposing(..), TopLevelExpose(..))
import Elm.Syntax.Expression exposing (Expression(..), RecordSetter)
import Elm.Syntax.Infix exposing (InfixDirection(..))
import Elm.Syntax.Module exposing (Module(..))
import Elm.Syntax.Node exposing (Node(..))
import Elm.Syntax.Pattern
import Elm.Syntax.Range exposing (emptyRange)
import Elm.Syntax.TypeAnnotation exposing (TypeAnnotation(..))
import Json.Decode as D exposing (Decoder)
import Json.Encode
import String.Case exposing (toCamelCaseLower)
import Writer


node =
    Node emptyRange


wrapNodes =
    List.map node


styleCode : Decoder String
styleCode =
    D.map (file >> Writer.writeFile >> Writer.write) style


declarations styleDec =
    [ FunctionDeclaration
        { documentation = Nothing
        , signature =
            Just
                (node
                    { name = node "style"
                    , typeAnnotation = node (Typed (node ( [], "Style" )) [])
                    }
                )
        , declaration =
            node
                { name = node "style"
                , arguments = []
                , expression =
                    node <|
                        Application <|
                            wrapNodes
                                [ FunctionOrValue [] "Style"
                                , RecordExpr styleDec
                                ]
                }
        }
    ]


file styleDec =
    { moduleDefinition =
        node
            (NormalModule
                { moduleName = node [ "Style" ]
                , exposingList = node (Explicit [ node (FunctionExpose "style") ])
                }
            )
    , imports =
        [ node
            { moduleName = node [ "Mapbox", "Style" ]
            , moduleAlias = Just (node [ "Style" ])
            , exposingList = Just (Explicit [ node (TypeExpose { name = "Style", open = Just emptyRange }) ])
            }
        , node
            { moduleName = node [ "Mapbox", "Source" ]
            , moduleAlias = Just (node [ "Source" ])
            , exposingList = Nothing
            }
        , node
            { moduleName = node [ "Mapbox", "Layer" ]
            , moduleAlias = Just (node [ "Layer" ])
            , exposingList = Nothing
            }
        , node
            { moduleName = node [ "Mapbox", "Expression" ]
            , moduleAlias = Just (node [ "E" ])
            , exposingList = Just (Explicit [ node (FunctionExpose "str"), node (FunctionExpose "float"), node (FunctionExpose "int"), node (FunctionExpose "true"), node (FunctionExpose "false") ])
            }
        ]
    , declarations = List.map node (declarations styleDec)
    , comments = []
    }


style : Decoder (List (Node RecordSetter))
style =
    D.map5
        (\transition light layers sources misc ->
            [ node ( node "transition", transition )
            , node ( node "light", light )
            , node ( node "layers", layers )
            , node ( node "sources", sources )
            , node ( node "misc", misc )
            ]
        )
        (D.oneOf
            [ D.field "transition" decodeTransition
            , valueDecoder "Style" "defaultTransition"
            ]
        )
        (D.oneOf
            [ D.field "light" decodeLight
            , valueDecoder "Style" "defaultLight"
            ]
        )
        (D.field "layers" decodeLayers)
        (D.field "sources" decodeSources)
        decodeMisc


decodeTransition : Decoder (Node Expression)
decodeTransition =
    D.map2
        (\duration delay ->
            node
                (RecordExpr
                    [ node ( node "duration", node (Integer duration) )
                    , node ( node "delay", node (Integer delay) )
                    ]
                )
        )
        (D.oneOf [ D.field "duration" D.int, D.succeed 300 ])
        (D.oneOf [ D.field "delay" D.int, D.succeed 0 ])


decodeLight : Decoder (Node Expression)
decodeLight =
    valueDecoder "Style" "defaultLight"


addBogusRange index (Node _ v) =
    Node { start = { row = index, column = 0 }, end = { row = index + 1, column = 0 } } v


decodeLayers : Decoder (Node Expression)
decodeLayers =
    D.list decodeLayer
        |> D.map (\layers -> node (ListExpr (List.indexedMap addBogusRange layers)))


layerDecodeHelp t =
    D.map3 (\id source attrs -> call "Layer" t [ str id, str source, list attrs ]) (D.field "id" D.string) (D.field "source" D.string) decodeAttrs


decodeLayer : Decoder (Node Expression)
decodeLayer =
    D.field "type" D.string
        |> D.andThen
            (\t ->
                case t of
                    "background" ->
                        D.map2 (\id attrs -> call "Layer" "background" [ str id, list attrs ]) (D.field "id" D.string) decodeAttrs

                    "fill" ->
                        layerDecodeHelp "fill"

                    "symbol" ->
                        layerDecodeHelp "symbol"

                    "line" ->
                        layerDecodeHelp "line"

                    "raster" ->
                        layerDecodeHelp "raster"

                    "circle" ->
                        layerDecodeHelp "circle"

                    "fill-extrusion" ->
                        layerDecodeHelp "fillExtrusion"

                    "heatmap" ->
                        layerDecodeHelp "heatmap"

                    "hillshade" ->
                        layerDecodeHelp "hillshade"

                    other ->
                        D.fail ("Layer type " ++ t ++ " not supported")
            )


decodeAttrs : Decoder (List (Node Expression))
decodeAttrs =
    D.map3 (\top paint layout -> top ++ paint ++ layout) (D.keyValuePairs D.value) (D.field "paint" (D.keyValuePairs D.value)) (D.field "layout" (D.keyValuePairs D.value))
        |> D.andThen
            (List.filterMap
                (\( attrName, attrValue ) ->
                    case attrName of
                        "id" ->
                            Nothing

                        "type" ->
                            Nothing

                        "source" ->
                            Nothing

                        "paint" ->
                            Nothing

                        "layout" ->
                            Nothing

                        "source-layer" ->
                            decodeAttr "sourceLayer" (D.map str D.string) attrValue

                        "minzoom" ->
                            decodeAttr "minzoom" (D.map float D.float) attrValue

                        "maxzoom" ->
                            decodeAttr "maxzoom" (D.map float D.float) attrValue

                        "filter" ->
                            decodeAttr "filter" (D.oneOf [ decodeLegacyFilter, decodeValue ]) attrValue

                        other ->
                            decodeAttr (toCamelCaseLower attrName) decodeValue attrValue
                )
                >> combine
            )
        |> D.map (List.indexedMap addBogusRange)


decodeAttr : String -> Decoder (Node Expression) -> D.Value -> Maybe (Decoder (Node Expression))
decodeAttr attrName expressionNodeDecoder attrValue =
    Just
        (D.decodeValue expressionNodeDecoder attrValue
            |> resultToDecoder
            |> D.map (\v -> call "Layer" (toCamelCaseLower attrName) [ v ])
        )


resultToDecoder : Result D.Error a -> Decoder a
resultToDecoder res =
    case res of
        Ok a ->
            D.succeed a

        Err e ->
            D.fail (D.errorToString e)


decodeBool : Decoder (Node Expression)
decodeBool =
    D.bool
        |> D.map
            (\b ->
                if b then
                    evalue "true"
                else
                    evalue "false"
            )


decodeValue : Decoder (Node Expression)
decodeValue =
    D.oneOf
        [ D.string |> D.map makeConstant
        , decodeBool
        , D.float |> D.map (Floatable >> node >> ecall "float")
        , D.int |> D.map (Integer >> node >> ecall "int")
        , D.index 0 D.string |> D.andThen decodeExpression
        , todo
        ]
        |> D.map (ParenthesizedExpression >> node)


makeConstant s =
    case s of
        "map" ->
            value "E" "anchorMap"

        "viewport" ->
            value "E" "anchorViewport"

        "auto" ->
            value "E" "anchorAuto"

        "center" ->
            value "E" "positionCenter"

        "left" ->
            value "E" "positionLeft"

        "right" ->
            value "E" "positionRight"

        "top" ->
            value "E" "positionTop"

        "bottom" ->
            value "E" "positionBottom"

        "topRight" ->
            value "E" "positionTopRight"

        "topLeft" ->
            value "E" "positionTopLeft"

        "bottomLeft" ->
            value "E" "positionBottomLeft"

        "bottomRight" ->
            value "E" "positionBottomRight"

        "none" ->
            value "E" "textFitNone"

        "width" ->
            value "E" "textFitWidth"

        "height" ->
            value "E" "textFitHeight"

        "both" ->
            value "E" "textFitBoth"

        "butt" ->
            value "E" "lineCapButt"

        "round" ->
            value "E" "lineCapRound"

        "square" ->
            value "E" "lineCapSquare"

        "bevel" ->
            value "E" "lineJoinBevel"

        "miter" ->
            value "E" "lineJoinMiter"

        "point" ->
            value "E" "symbolPlacementPoint"

        "line-center" ->
            value "E" "symbolPlacementLineCenter"

        "line" ->
            value "E" "symbolPlacementLine"

        "uppercase" ->
            value "E" "textTransformUppercase"

        "lowercase" ->
            value "E" "textTransformLowercase"

        "linear" ->
            value "E" "rasterResamplingLinear"

        "nearest" ->
            value "E" "rasterResamplingNearest"

        _ ->
            case Color.parse s of
                Ok { r, g, b, a } ->
                    call "E" "rgba" [ integer r, integer g, integer b, float a ]

                Err err ->
                    str s |> ecall "str"



-- legacy filter


decodeLegacyFilter : Decoder (Node Expression)
decodeLegacyFilter =
    let
        decodeProp =
            D.index 1 D.string
                |> D.map
                    (\prop ->
                        case prop of
                            "$type" ->
                                value "E" "geometryType"

                            "$id" ->
                                value "E" "id"

                            _ ->
                                call "E" "getProperty" [ ecall "str" (str prop) ]
                    )

        decodeVal =
            D.index 2 <|
                D.oneOf
                    [ D.map (str >> ecall "str") D.string
                    , D.map (float >> ecall "float") D.float
                    , decodeBool
                    ]

        decodeVals =
            D.list <|
                D.oneOf
                    [ D.map (str >> ecall "str") D.string
                    , D.map (float >> ecall "float") D.float
                    , decodeBool
                    ]
    in
    D.index 0 D.string
        |> D.andThen
            (\filter ->
                case filter of
                    "all" ->
                        decodeTail decodeLegacyFilter |> D.map (\filters -> call "E" "all" [ list filters ])

                    "any" ->
                        decodeTail decodeLegacyFilter |> D.map (\filters -> call "E" "any" [ list filters ])

                    "none" ->
                        decodeTail decodeLegacyFilter |> D.map (\filters -> call "E" "all" [ list (List.map (\f -> call "E" "not" [ f ]) filters) ])

                    "has" ->
                        D.index 1 D.string |> D.map (\prop -> call "E" "hasProperty" [ ecall "str" (str prop) ])

                    "!has" ->
                        D.index 1 D.string |> D.map (\prop -> call "E" "not" [ call "E" "hasProperty" [ ecall "str" (str prop) ] ])

                    "==" ->
                        D.map2 (\prop val -> pipelineCall "E" "isEqual" [ prop, val ]) decodeProp decodeVal

                    "!=" ->
                        D.map2 (\prop val -> pipelineCall "E" "notEqual" [ prop, val ]) decodeProp decodeVal

                    ">" ->
                        D.map2 (\prop val -> pipelineCall "E" "greaterThan" [ prop, val ]) decodeProp decodeVal

                    ">=" ->
                        D.map2 (\prop val -> pipelineCall "E" "greaterThanOrEqual" [ prop, val ]) decodeProp decodeVal

                    "<" ->
                        D.map2 (\prop val -> pipelineCall "E" "lessThan" [ prop, val ]) decodeProp decodeVal

                    "<=" ->
                        D.map2 (\prop val -> pipelineCall "E" "lessThanOrEqual" [ prop, val ]) decodeProp decodeVal

                    "in" ->
                        D.map2
                            (\prop values ->
                                List.drop 2 values
                                    |> List.map (\v -> pipelineCall "E" "isEqual" [ prop, v ])
                                    |> list
                                    |> List.singleton
                                    |> call "E" "any"
                            )
                            decodeProp
                            decodeVals

                    "!in" ->
                        D.map2
                            (\prop values ->
                                List.drop 2 values
                                    |> List.map (\v -> pipelineCall "E" "notEqual" [ prop, v ])
                                    |> list
                                    |> List.singleton
                                    |> call "E" "all"
                            )
                            decodeProp
                            decodeVals

                    _ ->
                        D.fail "not actually a legacy filter"
            )



-- Expressions


decodeTail : Decoder a -> Decoder (List a)
decodeTail itemDecoder =
    D.list D.value
        |> D.andThen
            (\l ->
                case l of
                    [] ->
                        D.fail "Can't get tail of empty"

                    head :: t ->
                        List.map (subdecode itemDecoder) t |> combine
            )


subdecode : Decoder a -> D.Value -> Decoder a
subdecode d v =
    D.decodeValue d v |> resultToDecoder


decodeMatch : Bool -> any -> Decoder (Node Expression)
decodeMatch isString _ =
    decodeTail D.value
        |> D.andThen
            (\args ->
                case args of
                    [] ->
                        todo

                    head :: tail ->
                        D.map2
                            (\cond rest ->
                                parens
                                    (node
                                        (OperatorApplication "|>"
                                            Right
                                            cond
                                            (call "E"
                                                (if isString then
                                                    "matchesStr"
                                                 else
                                                    "matchesFloat"
                                                )
                                                rest
                                            )
                                        )
                                    )
                            )
                            (subdecode decodeValue head)
                            (organizeArgs
                                (if isString then
                                    D.map str D.string
                                 else
                                    D.map float D.float
                                )
                                []
                                tail
                            )
            )


organizeArgs : Decoder (Node Expression) -> List (Decoder (Node Expression)) -> List D.Value -> Decoder (List (Node Expression))
organizeArgs inpDec accu args =
    case args of
        [] ->
            combine [ D.map list (List.reverse accu |> combine) ]

        [ default ] ->
            combine [ D.map list (List.reverse accu |> combine), subdecode decodeValue default ]

        a :: b :: rest ->
            let
                newAccu =
                    D.map2
                        (\inp out ->
                            parens (node (TupledExpression [ inp, out ]))
                        )
                        (subdecode inpDec a)
                        (subdecode decodeValue b)
                        :: accu
            in
            organizeArgs inpDec newAccu rest


decodeExpression : String -> Decoder (Node Expression)
decodeExpression funName =
    case funName of
        "literal" ->
            D.index 1
                (D.oneOf
                    [ D.list D.string |> D.map (\strs -> call "E" "strings" [ list (List.map str strs) ])
                    , D.list D.float |> D.map (\floats -> call "E" "floats" [ list (List.map float floats) ])
                    ]
                )

        "match" ->
            D.oneOf
                [ D.index 2 D.string |> D.andThen (decodeMatch True)
                , D.index 2 D.float |> D.andThen (decodeMatch False)
                ]

        "exponential" ->
            D.map (\base -> call "E" "Exponential" [ float base ]) (D.index 1 D.float)

        "interpolate" ->
            D.map3
                (\interpolation options input ->
                    pipelineCall "E" "interpolate" (input :: interpolation :: options)
                )
                (D.index 1 decodeValue)
                (decodeTail D.value |> D.map (List.drop 2) |> D.andThen (organizeArgs (D.map float D.float) []))
                (D.index 2 decodeValue)

        "step" ->
            D.map3
                (\inp def stps ->
                    pipelineCall "E" "step" (inp :: def :: stps)
                )
                (D.index 1 decodeValue)
                (D.index 2 decodeValue)
                (decodeTail D.value |> D.map (List.drop 2) |> D.andThen (organizeArgs (D.map float D.float) []))

        _ ->
            let
                fallback =
                    decodeTail decodeValue
                        |> D.map
                            (\arguments ->
                                case funName of
                                    "==" ->
                                        pipelineCall "E" "isEqual" arguments

                                    "!=" ->
                                        pipelineCall "E" "notEqual" arguments

                                    "!has" ->
                                        todoExpr "!has is not supported"

                                    "!in" ->
                                        todoExpr "!in is not supported"

                                    "in" ->
                                        todoExpr "in is not supported"

                                    ">=" ->
                                        pipelineCall "E" "greaterThanOrEqual" arguments

                                    "<=" ->
                                        pipelineCall "E" "lessThanOrEqual" arguments

                                    "concat" ->
                                        pipelineCall "E" "append" arguments

                                    "linear" ->
                                        call "E" "Linear" arguments

                                    "rgb" ->
                                        call "E" "makeRGBColor" arguments

                                    "rgba" ->
                                        call "E" "makeRGBAColor" arguments

                                    "to-rgba" ->
                                        call "E" "rgbaChannels" arguments

                                    "-" ->
                                        pipelineCall "E" "minus" arguments

                                    "*" ->
                                        pipelineCall "E" "multiply" arguments

                                    "+" ->
                                        pipelineCall "E" "plus" arguments

                                    "/" ->
                                        pipelineCall "E" "divideBy" arguments

                                    "%" ->
                                        pipelineCall "E" "modBy" arguments

                                    "^" ->
                                        pipelineCall "E" "raiseBy" arguments

                                    "get" ->
                                        if List.length arguments == 1 then
                                            call "E" "getProperty" arguments
                                        else
                                            call "E" "get" arguments

                                    _ ->
                                        call "E" (toCamelCaseLower funName) arguments
                            )
            in
            if String.toLower funName /= funName then
                D.oneOf
                    [ D.map (\strs -> call "E" "strings" [ list (List.map str strs) ]) <| D.list D.string
                    , fallback
                    ]
            else
                fallback


decodeSources : Decoder (Node Expression)
decodeSources =
    D.keyValuePairs decodeSource
        |> D.map (List.map (\( key, fn ) -> fn key))
        |> D.map (\sources -> node (ListExpr sources))


decodeSource : Decoder (String -> Node Expression)
decodeSource =
    D.field "type" D.string
        |> D.andThen
            (\t ->
                case t of
                    "vector" ->
                        D.field "url" D.string
                            |> D.map
                                (\url ->
                                    \id ->
                                        call "Source"
                                            "vectorFromUrl"
                                            [ str id
                                            , str url
                                            ]
                                )

                    _ ->
                        D.succeed (\a -> todoExpr ("type " ++ t ++ "not yet supported"))
            )


decodeMisc : Decoder (Node Expression)
decodeMisc =
    D.succeed (node (ListExpr []))


list l =
    node (ListExpr l)


str s =
    node (Literal s)


ecall name arg =
    parens (node (Application [ node (FunctionOrValue [] name), arg ]))


call ns name args =
    parens (node (Application (node (FunctionOrValue [ ns ] name) :: args)))


pipelineCall ns name args =
    case args of
        fst :: rest ->
            parens (node (OperatorApplication "|>" Left fst (call ns name rest)))

        _ ->
            todoExpr <| "Wrong number of arguments passed to " ++ ns ++ "." ++ name


value ns name =
    node (FunctionOrValue [ ns ] name)


evalue name =
    node (FunctionOrValue [] name)


integer =
    Integer >> node


float =
    Floatable >> node


parens =
    ParenthesizedExpression >> node


valueDecoder ns name =
    D.succeed (node (FunctionOrValue [ ns ] name))


todo : Decoder (Node Expression)
todo =
    D.map (\val -> todoExpr ("The expression " ++ Json.Encode.encode 0 val ++ " is not yet supported")) D.value


todoExpr msg =
    node (ParenthesizedExpression (call "Debug" "todo" [ str msg ]))


combine : List (Decoder a) -> Decoder (List a)
combine =
    List.foldr (D.map2 (::)) (D.succeed [])