Stabel

Check-in [71f2929943]
Login
Overview
Comment:Integers can now be represented directly in multifunction pattern matching. [c2996a5e70]
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: 71f292994379b8764bccccd16fe8936c7fa9eb2f31552a70bd6693539f9a2e47
User & Date: robin.hansen on 2021-09-24 09:35:36
Original Comment: Integers can now be represented directly in multifunction pattern matching.
Other Links: manifest | tags
Context
2021-09-24
09:39
Update dependencies. check-in: f61a4d953f user: robin.hansen tags: trunk
09:35
Integers can now be represented directly in multifunction pattern matching. [c2996a5e70] check-in: 71f2929943 user: robin.hansen tags: trunk
09:33
Consider all multifunctions with a default branch to be exhaustive. Closed-Leaf check-in: abd5404398 user: robin.hansen tags: int-literals-in-pattern-match
2021-09-20
16:33
Aliases can now be implicit [c2996a5e70] check-in: 7c8e530718 user: robin.hansen tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Modified src/Stabel/Codegen.elm from [8bebd10adc] to [91119aa4c4].

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
...
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
makeInequalityTest :
    List ( Type, Int )
    -> Int
    -> AST.TypeMatch
    -> Int
    -> Context
    -> ( Wasm.Instruction, Context )
makeInequalityTest boxMap selfIndex ((AST.TypeMatch _ typeFromTypeMatch _) as t_) localIdx context =
    let








        maybeBoxId =
            boxMap
                |> List.find (\( boxedType, _ ) -> Type.equalBaseType boxedType typeFromTypeMatch)
                |> Maybe.map Tuple.second
    in
    case ( t_, maybeBoxId ) of
        ( AST.TypeMatch _ Type.Int conditions, Just boxId ) ->
            ( Wasm.Batch
                [ Wasm.Local_Get localIdx
                , Wasm.I32_Load -- Load instance id
                , Wasm.I32_Const boxId
                , Wasm.I32_NotEq -- Types doesn't match?
                , Wasm.BreakIf 0 -- Move to next branch if above test is true
                , conditions
                    |> List.concatMap (matchingIntTest localIdx)

                    |> Wasm.Batch





                , Wasm.I32_Const selfIndex
                , BaseModule.callUnboxFn
                ]
            , context
            )

        ( AST.TypeMatch _ _ [], Just boxId ) ->
            ( Wasm.Batch
                [ Wasm.Local_Get localIdx
                , Wasm.I32_Load -- Load instance id
                , Wasm.I32_Const boxId
                , Wasm.I32_NotEq -- Types doesn't match?
                , Wasm.BreakIf 0 -- Move to next branch if above test is true
                , Wasm.I32_Const selfIndex
                , BaseModule.callUnboxFn
                ]
            , context
            )

        ( AST.TypeMatch _ (Type.Custom name) conditions, Nothing ) ->
            matchingStructTest boxMap selfIndex context localIdx name conditions

        ( AST.TypeMatch _ (Type.CustomGeneric name _) conditions, Nothing ) ->
            matchingStructTest boxMap selfIndex context localIdx name conditions

        _ ->
            -- Type not supported in pattern match
            -- TODO: TypeMatch should maybe change to only support types
            -- which are supported in pattern matches
            ( Wasm.Unreachable, context )


matchingIntTest : Int -> ( String, AST.TypeMatchValue ) -> List Wasm.Instruction
matchingIntTest localIdx ( _, astValue ) =
    let
        value =
            case astValue of
                AST.LiteralInt num ->
                    num

                _ ->
                    0
    in
    [ Wasm.Local_Get localIdx
    , Wasm.I32_Const BaseModule.wasmPtrSize
    , Wasm.I32_Add
    , Wasm.I32_Load -- int value
    , Wasm.I32_Const value
    , Wasm.I32_NotEq -- not same number?
    , Wasm.BreakIf 0 -- move to next branch
    ]


matchingStructTest :
    List ( Type, Int )
    -> Int
    -> Context
    -> Int
    -> String
    -> List ( String, AST.TypeMatchValue )
    -> ( Wasm.Instruction, Context )
matchingStructTest boxMap selfIndex context localIdx typeName conditions =
    let
        ( typeId, updatedContext ) =
            idForType typeName context

        ( conditionTestImpls, finalContext ) =
................................................................................
    )


matchingConditionTest :
    List ( Type, Int )
    -> Int
    -> Int
    -> ( String, AST.TypeMatchValue )
    -> ( List (List Wasm.Instruction), Context )
    -> ( List (List Wasm.Instruction), Context )
matchingConditionTest boxMap selfIndex localIdx ( fieldName, value ) ( result, context ) =
    let
        getterName =
            fieldName ++ ">"

................................................................................
        ( getterId, idContext ) =
            idForFunction getterName context

        callGetter =
            Wasm.Call getterId getterName
    in
    case value of
        AST.LiteralInt num ->
            ( [ Wasm.Local_Get localIdx
              , BaseModule.callStackPushFn
              , callGetter
              , BaseModule.callStackPopFn
              , Wasm.I32_Const num
              , Wasm.I32_NotEq -- not same number?
              , Wasm.BreakIf 0 -- move to next branch
              ]
                :: result
            , idContext
            )

        AST.LiteralType typ_ ->
            case typ_ of
                Type.Custom typeName ->
                    let
                        ( typeId, updatedContext ) =
                            idForType typeName idContext
                    in
                    ( [ Wasm.Local_Get localIdx
                      , BaseModule.callStackPushFn
                      , callGetter
                      , BaseModule.callStackPopFn
                      , Wasm.I32_Load -- get type id
                      , Wasm.I32_Const typeId
                      , Wasm.I32_NotEq -- not same type?
                      , Wasm.BreakIf 0 -- move to next branch
                      ]
                        :: result
                    , updatedContext
                    )

                _ ->
                    ( [ Wasm.Unreachable ] :: result
                    , context
                    )

        AST.RecursiveMatch match ->
            let
                nextLocalIdx =
                    localIdx + 1

                ( inequalityTestImpl, updatedContext ) =
                    makeInequalityTest boxMap selfIndex match nextLocalIdx idContext
            in







|

>
>
>
>
>
>
>
>





|
|






|
|
>
|
>
>
>
>
>






|












|


|








<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







|







 







|







 







|












<
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
<
<
<
<
<







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
...
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
makeInequalityTest :
    List ( Type, Int )
    -> Int
    -> AST.TypeMatch
    -> Int
    -> Context
    -> ( Wasm.Instruction, Context )
makeInequalityTest boxMap selfIndex match localIdx context =
    let
        typeFromTypeMatch =
            case match of
                AST.TypeMatchInt _ _ ->
                    Type.Int

                AST.TypeMatchType _ tipe _ ->
                    tipe

        maybeBoxId =
            boxMap
                |> List.find (\( boxedType, _ ) -> Type.equalBaseType boxedType typeFromTypeMatch)
                |> Maybe.map Tuple.second
    in
    case ( match, maybeBoxId ) of
        ( AST.TypeMatchInt _ value, Just boxId ) ->
            ( Wasm.Batch
                [ Wasm.Local_Get localIdx
                , Wasm.I32_Load -- Load instance id
                , Wasm.I32_Const boxId
                , Wasm.I32_NotEq -- Types doesn't match?
                , Wasm.BreakIf 0 -- Move to next branch if above test is true
                , Wasm.Batch
                    [ Wasm.Local_Get localIdx
                    , Wasm.I32_Const BaseModule.wasmPtrSize
                    , Wasm.I32_Add
                    , Wasm.I32_Load -- int value
                    , Wasm.I32_Const value
                    , Wasm.I32_NotEq -- not same number?
                    , Wasm.BreakIf 0 -- move to next branch
                    ]
                , Wasm.I32_Const selfIndex
                , BaseModule.callUnboxFn
                ]
            , context
            )

        ( AST.TypeMatchType _ _ [], Just boxId ) ->
            ( Wasm.Batch
                [ Wasm.Local_Get localIdx
                , Wasm.I32_Load -- Load instance id
                , Wasm.I32_Const boxId
                , Wasm.I32_NotEq -- Types doesn't match?
                , Wasm.BreakIf 0 -- Move to next branch if above test is true
                , Wasm.I32_Const selfIndex
                , BaseModule.callUnboxFn
                ]
            , context
            )

        ( AST.TypeMatchType _ (Type.Custom name) conditions, Nothing ) ->
            matchingStructTest boxMap selfIndex context localIdx name conditions

        ( AST.TypeMatchType _ (Type.CustomGeneric name _) conditions, Nothing ) ->
            matchingStructTest boxMap selfIndex context localIdx name conditions

        _ ->
            -- Type not supported in pattern match
            -- TODO: TypeMatch should maybe change to only support types
            -- which are supported in pattern matches
            ( Wasm.Unreachable, context )























matchingStructTest :
    List ( Type, Int )
    -> Int
    -> Context
    -> Int
    -> String
    -> List ( String, AST.TypeMatch )
    -> ( Wasm.Instruction, Context )
matchingStructTest boxMap selfIndex context localIdx typeName conditions =
    let
        ( typeId, updatedContext ) =
            idForType typeName context

        ( conditionTestImpls, finalContext ) =
................................................................................
    )


matchingConditionTest :
    List ( Type, Int )
    -> Int
    -> Int
    -> ( String, AST.TypeMatch )
    -> ( List (List Wasm.Instruction), Context )
    -> ( List (List Wasm.Instruction), Context )
matchingConditionTest boxMap selfIndex localIdx ( fieldName, value ) ( result, context ) =
    let
        getterName =
            fieldName ++ ">"

................................................................................
        ( getterId, idContext ) =
            idForFunction getterName context

        callGetter =
            Wasm.Call getterId getterName
    in
    case value of
        AST.TypeMatchInt _ num ->
            ( [ Wasm.Local_Get localIdx
              , BaseModule.callStackPushFn
              , callGetter
              , BaseModule.callStackPopFn
              , Wasm.I32_Const num
              , Wasm.I32_NotEq -- not same number?
              , Wasm.BreakIf 0 -- move to next branch
              ]
                :: result
            , idContext
            )



        AST.TypeMatchType _ (Type.Custom typeName) [] ->
            let
                ( typeId, updatedContext ) =
                    idForType typeName idContext
            in
            ( [ Wasm.Local_Get localIdx
              , BaseModule.callStackPushFn
              , callGetter
              , BaseModule.callStackPopFn
              , Wasm.I32_Load -- get type id
              , Wasm.I32_Const typeId
              , Wasm.I32_NotEq -- not same type?
              , Wasm.BreakIf 0 -- move to next branch
              ]
                :: result
            , updatedContext
            )

        match ->





            let
                nextLocalIdx =
                    localIdx + 1

                ( inequalityTestImpl, updatedContext ) =
                    makeInequalityTest boxMap selfIndex match nextLocalIdx idContext
            in

Modified src/Stabel/Parser.elm from [6bb3a2d289] to [0ae4b446a0].

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..
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
....
1338
1339
1340
1341
1342
1343
1344

1345
1346




1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359







1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
    ( AST
    , AstNode(..)
    , FunctionDefinition
    , FunctionImplementation(..)
    , TypeDefinition
    , TypeDefinitionMembers(..)
    , TypeMatch(..)
    , TypeMatchValue(..)
    , run
    )

import Bitwise
import Dict exposing (Dict)
import Dict.Extra as Dict
import List.Extra as List
................................................................................
    , imports : Dict String (List String)
    , implementation : FunctionImplementation
    }


type FunctionImplementation
    = SoloImpl (List AstNode)

    | MultiImpl (List ( TypeMatch, List AstNode )) (List AstNode)


type TypeMatch

    = TypeMatch SourceLocationRange PossiblyQualifiedType (List ( String, TypeMatchValue ))


type TypeMatchValue
    = LiteralInt Int
    | LiteralType PossiblyQualifiedType
    | RecursiveMatch TypeMatch


type AstNode
    = Integer SourceLocationRange Int
    | Function SourceLocationRange String
    | PackageFunction SourceLocationRange (List String) String
    | ExternalFunction SourceLocationRange (List String) String
................................................................................
            |. noiseParser
        , Parser.succeed (Parser.Done (List.reverse reverseTypes))
        ]


typeMatchParser : Parser TypeMatch
typeMatchParser =

    Parser.succeed (\startLoc type_ conds endLoc -> TypeMatch (SourceLocationRange startLoc endLoc) type_ conds)
        |= sourceLocationParser




        |= typeMatchTypeParser
        |= Parser.oneOf
            [ Parser.succeed identity
                |. Parser.symbol (Token "(" ExpectedLeftParen)
                |. noiseParser
                |= Parser.loop [] typeMatchConditionParser
                |. Parser.symbol (Token ")" ExpectedRightParen)
            , Parser.succeed []
            ]
        |= sourceLocationParser


typeMatchConditionParser : List ( String, TypeMatchValue ) -> Parser (Parser.Step (List ( String, TypeMatchValue )) (List ( String, TypeMatchValue )))







typeMatchConditionParser nodes =
    Parser.oneOf
        [ Parser.succeed (\name value -> Parser.Loop (( name, value ) :: nodes))
            |= symbolParser
            |. noiseParser
            |= typeMatchValueParser
            |. noiseParser
        , Parser.succeed (Parser.Done (List.reverse nodes))
        ]


typeMatchValueParser : Parser TypeMatchValue
typeMatchValueParser =
    let
        handleNewType ((TypeMatch _ type_ conditions) as match) =
            case conditions of
                [] ->
                    LiteralType type_

                _ ->
                    RecursiveMatch match
    in
    Parser.oneOf
        [ Parser.succeed LiteralInt
            |= intParser
        , Parser.succeed handleNewType
            |= typeMatchParser
        ]


implementationParser : Parser (List AstNode)
implementationParser =
    Parser.loop [] implementationParserHelp


implementationParserHelp : List AstNode -> Parser (Parser.Step (List AstNode) (List AstNode))







<







 







>




>
|
<
<
<
<
<
<







 







>
|
|
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|

<
>
>
>
>
>
>
>





|




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







2
3
4
5
6
7
8

9
10
11
12
13
14
15
..
63
64
65
66
67
68
69
70
71
72
73
74
75
76






77
78
79
80
81
82
83
....
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375



















1376
1377
1378
1379
1380
1381
1382
    ( AST
    , AstNode(..)
    , FunctionDefinition
    , FunctionImplementation(..)
    , TypeDefinition
    , TypeDefinitionMembers(..)
    , TypeMatch(..)

    , run
    )

import Bitwise
import Dict exposing (Dict)
import Dict.Extra as Dict
import List.Extra as List
................................................................................
    , imports : Dict String (List String)
    , implementation : FunctionImplementation
    }


type FunctionImplementation
    = SoloImpl (List AstNode)
      -- TODO: Default branch should be a (Maybe (List AstNode))
    | MultiImpl (List ( TypeMatch, List AstNode )) (List AstNode)


type TypeMatch
    = TypeMatchInt SourceLocationRange Int
    | TypeMatchType SourceLocationRange PossiblyQualifiedType (List ( String, TypeMatch ))








type AstNode
    = Integer SourceLocationRange Int
    | Function SourceLocationRange String
    | PackageFunction SourceLocationRange (List String) String
    | ExternalFunction SourceLocationRange (List String) String
................................................................................
            |. noiseParser
        , Parser.succeed (Parser.Done (List.reverse reverseTypes))
        ]


typeMatchParser : Parser TypeMatch
typeMatchParser =
    Parser.oneOf
        [ Parser.succeed (\startLoc int endLoc -> TypeMatchInt (SourceLocationRange startLoc endLoc) int)
            |= sourceLocationParser
            |= intParser
            |= sourceLocationParser
        , Parser.succeed typeMatchTypeHelper
            |= sourceLocationParser
            |= typeMatchTypeParser
            |= Parser.oneOf
                [ Parser.succeed identity
                    |. Parser.symbol (Token "(" ExpectedLeftParen)
                    |. noiseParser
                    |= Parser.loop [] typeMatchConditionParser
                    |. Parser.symbol (Token ")" ExpectedRightParen)
                , Parser.succeed []
                ]
            |= sourceLocationParser
        ]



typeMatchTypeHelper : SourceLocation -> PossiblyQualifiedType -> List ( String, TypeMatch ) -> SourceLocation -> TypeMatch
typeMatchTypeHelper startLoc type_ conds endLoc =
    TypeMatchType (SourceLocationRange startLoc endLoc) type_ conds


typeMatchConditionParser : List ( String, TypeMatch ) -> Parser (Parser.Step (List ( String, TypeMatch )) (List ( String, TypeMatch )))
typeMatchConditionParser nodes =
    Parser.oneOf
        [ Parser.succeed (\name value -> Parser.Loop (( name, value ) :: nodes))
            |= symbolParser
            |. noiseParser
            |= typeMatchParser
            |. noiseParser
        , Parser.succeed (Parser.Done (List.reverse nodes))
        ]





















implementationParser : Parser (List AstNode)
implementationParser =
    Parser.loop [] implementationParserHelp


implementationParserHelp : List AstNode -> Parser (Parser.Step (List AstNode) (List AstNode))

Modified src/Stabel/Qualifier.elm from [ff52ef351a] to [8ec9cb1f71].

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
..
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
...
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923






924


925
926
927
928



929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957




958


959
960
961
962
963
964
965
966
967




968


969
970
971
972
973
974
975
976
977




978


979
980
981
982
983
984
985
986
987
988
989




990


991
992
993
994
995
996

997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010




1011
1012
1013
1014






1015


1016
1017


1018




1019










1020

1021


1022
1023
























1024
1025
1026
1027
1028
1029
1030
1031
1032

1033
1034
1035
1036
1037
1038
1039
....
1726
1727
1728
1729
1730
1731
1732
1733





1734
1735
1736
1737
1738
1739
1740
1741
    , FunctionDefinition
    , FunctionImplementation(..)
    , Node(..)
    , RunConfig
    , TypeDefinition
    , TypeDefinitionMembers(..)
    , TypeMatch(..)
    , TypeMatchCond(..)
    , TypeMatchValue(..)
    , requiredModules
    , run
    )

import Dict exposing (Dict)
import List.Extra as List
import Result.Extra as Result
................................................................................

type FunctionImplementation
    = SoloImpl (List Node)
    | MultiImpl (List ( TypeMatch, List Node )) (List Node)


type TypeMatch

    = TypeMatch SourceLocationRange Type (List TypeMatchCond)


type TypeMatchCond
    = TypeMatchCond String Type TypeMatchValue


type TypeMatchValue
    = LiteralInt Int
    | LiteralType Type
    | RecursiveMatch TypeMatch


type Node
    = Integer SourceLocationRange Int
    | Function SourceLocationRange FunctionDefinition
    | FunctionRef SourceLocationRange FunctionDefinition
    | Recurse SourceLocationRange
................................................................................
qualifyMatch config qualifiedTypes modRefs typeMatch =
    let
        qualifiedRange range =
            SourceLocationRange
                config.ast.sourceReference
                range.start
                range.end

        qualifiedNameToMatch range name patterns =
            case Dict.get name qualifiedTypes of
                Just typeDef ->
                    if not typeDef.exposed then
                        Err <| TypeNotExposed range name

                    else
                        case typeDef.members of
                            StructMembers members ->
                                let
                                    qualifiedPatternsResult =
                                        patterns
                                            |> List.map
                                                (qualifyMatchValue
                                                    config
                                                    qualifiedTypes
                                                    modRefs
                                                    range
                                                    name
                                                    members
                                                )
                                            |> Result.combine

                                    actualType =
                                        case typeDef.generics of
                                            [] ->
                                                Type.Custom name

                                            _ ->
                                                Type.CustomGeneric
                                                    name
                                                    (List.map Type.Generic typeDef.generics)
                                in
                                case qualifiedPatternsResult of
                                    Ok qualifiedPatterns ->
                                        Ok <| TypeMatch range actualType qualifiedPatterns

                                    Err err ->
                                        Err err

                            UnionMembers types ->
                                if List.isEmpty patterns then
                                    Ok <| TypeMatch range (Type.Union (Just name) types) []

                                else
                                    Err <| UnionTypeMatchWithPatterns range

                Nothing ->
                    Err <| UnknownTypeRef range name
    in
    case typeMatch of
        Parser.TypeMatch range (Parser.LocalRef "Int" []) [] ->
            Ok <| TypeMatch (qualifiedRange range) Type.Int []

        Parser.TypeMatch range (Parser.LocalRef "Int" []) [ ( "value", Parser.LiteralInt val ) ] ->
            Ok <|
                TypeMatch
                    (qualifiedRange range)
                    Type.Int
                    [ TypeMatchCond "value" Type.Int (LiteralInt val) ]

        Parser.TypeMatch range (Parser.LocalRef "Array" []) [] ->
            Ok <|
                TypeMatch
                    (qualifiedRange range)
                    (Type.Array (Type.Generic "*a"))
                    []

        Parser.TypeMatch range (Parser.Generic sym) [] ->
            Ok <| TypeMatch (qualifiedRange range) (Type.Generic sym) []

        Parser.TypeMatch range (Parser.LocalRef name []) patterns ->






            case qualifiedNameToMatch (qualifiedRange range) (qualifyName config name) patterns of


                (Err (UnknownTypeRef _ _)) as errMsg ->
                    case resolveImportedType config modRefs name of
                        Just importedModule ->
                            qualifiedNameToMatch



                                (qualifiedRange range)
                                (importedModule ++ "/" ++ name)
                                patterns

                        Nothing ->
                            errMsg

                result ->
                    result

        Parser.TypeMatch range (Parser.InternalRef [ possibleAlias ] name _) patterns ->
            case Dict.get possibleAlias modRefs.aliases of
                Just actualPath ->
                    if representsExternalModule actualPath then
                        let
                            extPath =
                                splitExternalPackagePath actualPath
                        in
                        qualifyMatch config qualifiedTypes modRefs <|
                            Parser.TypeMatch range (Parser.ExternalRef extPath name []) patterns

                    else
                        let
                            qualifiedName =
                                actualPath
                                    ++ "/"
                                    ++ name
                                    |> qualifyPackageModule config.packageName
                        in




                        qualifiedNameToMatch (qualifiedRange range) qualifiedName patterns



                Nothing ->
                    let
                        qualifiedName =
                            possibleAlias
                                ++ "/"
                                ++ name
                                |> qualifyPackageModule config.packageName
                    in




                    qualifiedNameToMatch (qualifiedRange range) qualifiedName patterns



        Parser.TypeMatch range (Parser.InternalRef path name _) patterns ->
            let
                qualifiedName =
                    path
                        ++ [ name ]
                        |> String.join "/"
                        |> qualifyPackageModule config.packageName
            in




            qualifiedNameToMatch (qualifiedRange range) qualifiedName patterns



        Parser.TypeMatch range (Parser.ExternalRef path name _) patterns ->
            let
                pathString =
                    "/" ++ String.join "/" path

                qualifiedName =
                    Dict.get pathString config.externalModules
                        |> Maybe.map (\prefix -> "/" ++ prefix ++ pathString ++ "/" ++ name)
                        |> Maybe.withDefault ""
            in




            qualifiedNameToMatch (qualifiedRange range) qualifiedName patterns



        Parser.TypeMatch range _ _ ->
            Err <| InvalidTypeMatch (qualifiedRange range)


qualifyMatchValue :

    RunConfig
    -> Dict String TypeDefinition
    -> ModuleReferences
    -> SourceLocationRange
    -> String
    -> List ( String, Type )
    -> ( String, Parser.TypeMatchValue )
    -> Result Problem TypeMatchCond
qualifyMatchValue config qualifiedTypes modRefs range typeName members ( fieldName, matchValue ) =
    case List.find ((==) fieldName << Tuple.first) members of
        Just ( _, fieldType ) ->
            case matchValue of
                Parser.LiteralInt val ->
                    Ok <| TypeMatchCond fieldName fieldType (LiteralInt val)





                Parser.LiteralType type_ ->
                    type_
                        |> qualifyMemberType config modRefs range






                        |> Result.map


                            (\qualifiedType ->
                                TypeMatchCond


                                    fieldName




                                    fieldType










                                    (LiteralType qualifiedType)

                            )



                Parser.RecursiveMatch typeMatch ->
























                    typeMatch
                        |> qualifyMatch config qualifiedTypes modRefs
                        |> Result.map
                            (\match ->
                                TypeMatchCond
                                    fieldName
                                    fieldType
                                    (RecursiveMatch match)
                            )


        _ ->
            Err <| NoSuchMemberOnType range typeName fieldName


initQualifyNode :
    RunConfig
................................................................................
                Parser.MultiImpl branches _ ->
                    branches
                        |> List.map Tuple.first
                        |> List.map extractMatchType
                        |> List.filterMap extractModuleReferenceFromType
                        |> Set.fromList

        extractMatchType (Parser.TypeMatch _ tipe _) =





            tipe

        impls =
            case function.implementation of
                Parser.SoloImpl impl ->
                    [ impl ]

                Parser.MultiImpl branches impl ->







<
<







 







>
|
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|
|

|
<
<
|
<
<

|

|




|
|

|
>
>
>
>
>
>
|
>
>




>
>
>










|








|









>
>
>
>
|
>
>









>
>
>
>
|
>
>

|







>
>
>
>
|
>
>

|









>
>
>
>
|
>
>

|



<
>





<
|
|
|
<
<
<
<
<
>
>
>
>

<
<
<
>
>
>
>
>
>
|
>
>
|
<
>
>
|
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
|
>
|
>
>

<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
<
|
|
|
|
>







 







|
>
>
>
>
>
|







4
5
6
7
8
9
10


11
12
13
14
15
16
17
..
69
70
71
72
73
74
75
76
77










78
79
80
81
82
83
84
...
833
834
835
836
837
838
839

































840

















841
842
843
844
845


846


847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965

966
967
968
969
970
971

972
973
974





975
976
977
978
979



980
981
982
983
984
985
986
987
988
989

990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013

1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041

1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
....
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
    , FunctionDefinition
    , FunctionImplementation(..)
    , Node(..)
    , RunConfig
    , TypeDefinition
    , TypeDefinitionMembers(..)
    , TypeMatch(..)


    , requiredModules
    , run
    )

import Dict exposing (Dict)
import List.Extra as List
import Result.Extra as Result
................................................................................

type FunctionImplementation
    = SoloImpl (List Node)
    | MultiImpl (List ( TypeMatch, List Node )) (List Node)


type TypeMatch
    = TypeMatchInt SourceLocationRange Int
    | TypeMatchType SourceLocationRange Type (List ( String, Type, TypeMatch ))












type Node
    = Integer SourceLocationRange Int
    | Function SourceLocationRange FunctionDefinition
    | FunctionRef SourceLocationRange FunctionDefinition
    | Recurse SourceLocationRange
................................................................................
qualifyMatch config qualifiedTypes modRefs typeMatch =
    let
        qualifiedRange range =
            SourceLocationRange
                config.ast.sourceReference
                range.start
                range.end

































    in

















    case typeMatch of
        Parser.TypeMatchInt range val ->
            Ok <| TypeMatchInt (qualifiedRange range) val

        Parser.TypeMatchType range (Parser.LocalRef "Int" []) [] ->


            Ok <| TypeMatchType (qualifiedRange range) Type.Int []



        Parser.TypeMatchType range (Parser.LocalRef "Array" []) [] ->
            Ok <|
                TypeMatchType
                    (qualifiedRange range)
                    (Type.Array (Type.Generic "*a"))
                    []

        Parser.TypeMatchType range (Parser.Generic sym) [] ->
            Ok <| TypeMatchType (qualifiedRange range) (Type.Generic sym) []

        Parser.TypeMatchType range (Parser.LocalRef name []) patterns ->
            case
                qualifiedNameToMatch
                    config
                    qualifiedTypes
                    modRefs
                    (qualifiedRange range)
                    (qualifyName config name)
                    patterns
            of
                (Err (UnknownTypeRef _ _)) as errMsg ->
                    case resolveImportedType config modRefs name of
                        Just importedModule ->
                            qualifiedNameToMatch
                                config
                                qualifiedTypes
                                modRefs
                                (qualifiedRange range)
                                (importedModule ++ "/" ++ name)
                                patterns

                        Nothing ->
                            errMsg

                result ->
                    result

        Parser.TypeMatchType range (Parser.InternalRef [ possibleAlias ] name _) patterns ->
            case Dict.get possibleAlias modRefs.aliases of
                Just actualPath ->
                    if representsExternalModule actualPath then
                        let
                            extPath =
                                splitExternalPackagePath actualPath
                        in
                        qualifyMatch config qualifiedTypes modRefs <|
                            Parser.TypeMatchType range (Parser.ExternalRef extPath name []) patterns

                    else
                        let
                            qualifiedName =
                                actualPath
                                    ++ "/"
                                    ++ name
                                    |> qualifyPackageModule config.packageName
                        in
                        qualifiedNameToMatch
                            config
                            qualifiedTypes
                            modRefs
                            (qualifiedRange range)
                            qualifiedName
                            patterns

                Nothing ->
                    let
                        qualifiedName =
                            possibleAlias
                                ++ "/"
                                ++ name
                                |> qualifyPackageModule config.packageName
                    in
                    qualifiedNameToMatch
                        config
                        qualifiedTypes
                        modRefs
                        (qualifiedRange range)
                        qualifiedName
                        patterns

        Parser.TypeMatchType range (Parser.InternalRef path name _) patterns ->
            let
                qualifiedName =
                    path
                        ++ [ name ]
                        |> String.join "/"
                        |> qualifyPackageModule config.packageName
            in
            qualifiedNameToMatch
                config
                qualifiedTypes
                modRefs
                (qualifiedRange range)
                qualifiedName
                patterns

        Parser.TypeMatchType range (Parser.ExternalRef path name _) patterns ->
            let
                pathString =
                    "/" ++ String.join "/" path

                qualifiedName =
                    Dict.get pathString config.externalModules
                        |> Maybe.map (\prefix -> "/" ++ prefix ++ pathString ++ "/" ++ name)
                        |> Maybe.withDefault ""
            in
            qualifiedNameToMatch
                config
                qualifiedTypes
                modRefs
                (qualifiedRange range)
                qualifiedName
                patterns

        Parser.TypeMatchType range _ _ ->
            Err <| InvalidTypeMatch (qualifiedRange range)



qualifiedNameToMatch :
    RunConfig
    -> Dict String TypeDefinition
    -> ModuleReferences
    -> SourceLocationRange
    -> String

    -> List ( String, Parser.TypeMatch )
    -> Result Problem TypeMatch
qualifiedNameToMatch config qualifiedTypes modRefs range name patterns =





    case Dict.get name qualifiedTypes of
        Just typeDef ->
            if not typeDef.exposed then
                Err <| TypeNotExposed range name




            else
                case typeDef.members of
                    StructMembers members ->
                        let
                            qualifiedPatternsResult =
                                patterns
                                    |> List.map
                                        (qualifyMatchValue
                                            config
                                            qualifiedTypes

                                            modRefs
                                            range
                                            name
                                            members
                                        )
                                    |> Result.combine

                            actualType =
                                case typeDef.generics of
                                    [] ->
                                        Type.Custom name

                                    _ ->
                                        Type.CustomGeneric
                                            name
                                            (List.map Type.Generic typeDef.generics)
                        in
                        case qualifiedPatternsResult of
                            Ok qualifiedPatterns ->
                                Ok <| TypeMatchType range actualType qualifiedPatterns

                            Err err ->
                                Err err


                    UnionMembers types ->
                        case patterns of
                            [] ->
                                Ok <| TypeMatchType range (Type.Union (Just name) types) []

                            _ ->
                                Err <| UnionTypeMatchWithPatterns range

        Nothing ->
            Err <| UnknownTypeRef range name


qualifyMatchValue :
    RunConfig
    -> Dict String TypeDefinition
    -> ModuleReferences
    -> SourceLocationRange
    -> String
    -> List ( String, Type )
    -> ( String, Parser.TypeMatch )
    -> Result Problem ( String, Type, TypeMatch )
qualifyMatchValue config qualifiedTypes modRefs range typeName members ( fieldName, matchValue ) =
    case List.find ((==) fieldName << Tuple.first) members of
        Just ( _, fieldType ) ->
            matchValue
                |> qualifyMatch config qualifiedTypes modRefs
                |> Result.map
                    (\match ->

                        ( fieldName
                        , fieldType
                        , match
                        )
                    )

        _ ->
            Err <| NoSuchMemberOnType range typeName fieldName


initQualifyNode :
    RunConfig
................................................................................
                Parser.MultiImpl branches _ ->
                    branches
                        |> List.map Tuple.first
                        |> List.map extractMatchType
                        |> List.filterMap extractModuleReferenceFromType
                        |> Set.fromList

        extractMatchType match =
            case match of
                Parser.TypeMatchInt _ _ ->
                    Parser.LocalRef "Int" []

                Parser.TypeMatchType _ tipe _ ->
                    tipe

        impls =
            case function.implementation of
                Parser.SoloImpl impl ->
                    [ impl ]

                Parser.MultiImpl branches impl ->

Modified src/Stabel/TypeChecker.elm from [cb83d58fcb] to [8902188c94].

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..
43
44
45
46
47
48
49

50
51
52
53
54
55
56
57
58
59
60
61
62
63
...
414
415
416
417
418
419
420
421
422
423
424



425
426
427
428
429
430
431
...
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
...
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
...
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
...
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
...
707
708
709
710
711
712
713
714




715
716
717
718
719
720
721
...
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
...
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
....
1077
1078
1079
1080
1081
1082
1083
1084
1085


1086
1087

1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114




1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131








1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155


1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
    ( AST
    , AstNode(..)
    , CycleData
    , FunctionDefinition
    , FunctionImplementation(..)
    , TypeDefinition
    , TypeMatch(..)
    , TypeMatchValue(..)
    , run
    )

import Dict exposing (Dict)
import List.Extra as List
import Result.Extra as Result
import Set exposing (Set)
................................................................................

type FunctionImplementation
    = SoloImpl (List AstNode)
    | MultiImpl (List ( TypeMatch, List AstNode )) (List AstNode)


type TypeMatch

    = TypeMatch SourceLocationRange Type (List ( String, TypeMatchValue ))


type TypeMatchValue
    = LiteralInt Int
    | LiteralType Type
    | RecursiveMatch TypeMatch


type AstNode
    = IntLiteral SourceLocationRange Int
    | ArrayLiteral SourceLocationRange (List AstNode) Type
    | Function SourceLocationRange FunctionDefinition FunctionType
    | FunctionRef SourceLocationRange FunctionDefinition
................................................................................
                                untypedDef
                                untypedDef.typeSignature
                                defaultImpl
                                (cleanContext context)
                    in
                    case inferredDefaultType.input of
                        [] ->
                            ( Qualifier.TypeMatch SourceLocation.emptyRange (Type.Generic "*") [], defaultImpl ) :: initialWhens

                        firstType :: _ ->
                            ( Qualifier.TypeMatch SourceLocation.emptyRange firstType [], defaultImpl ) :: initialWhens




        whens =
            List.map (Tuple.mapFirst (resolveWhenConditions untypedDef)) allBranches

        ( inferredWhenTypes, newContext ) =
            whens
                |> List.foldr (inferWhenTypes untypedDef) ( [], context )
................................................................................
            if whensAreConsistent && whensAreCompatible then
                Nothing

            else
                Just <| InconsistentWhens sourceLocation untypedDef.name

        maybeInexhaustiveError =
            inexhaustivenessCheck sourceLocation whenPatterns

        sourceLocation =
            Maybe.withDefault SourceLocation.emptyRange untypedDef.sourceLocation

        typedDef =
            { name = untypedDef.name
            , sourceLocation = untypedDef.sourceLocation
................................................................................
    in
    ( typedDef
    , finalContext
    )


resolveWhenConditions : Qualifier.FunctionDefinition -> Qualifier.TypeMatch -> Qualifier.TypeMatch
resolveWhenConditions untypedDef ((Qualifier.TypeMatch loc typeMatch conds) as match) =
    case typeMatch of
        Type.CustomGeneric _ structGenerics ->
            let
                bindings =
                    List.foldl
                        whenConditionsGenericBindings
                        (initialBindingsFromFunctionDef untypedDef structGenerics)
                        conds
            in
            Qualifier.TypeMatch
                loc
                (bindGenericsInType bindings typeMatch)
                (List.map (whenConditionsBindGenerics bindings) conds)

        _ ->
            match


initialBindingsFromFunctionDef : Qualifier.FunctionDefinition -> List Type -> Dict String Type
................................................................................
                _ ->
                    Dict.empty

        Nothing ->
            Dict.empty


whenConditionsGenericBindings : Qualifier.TypeMatchCond -> Dict String Type -> Dict String Type
whenConditionsGenericBindings (Qualifier.TypeMatchCond _ fieldType value) bindings =
    case ( fieldType, value ) of
        ( Type.Generic genericName, Qualifier.LiteralInt _ ) ->
            Dict.insert genericName Type.Int bindings

        ( Type.Generic genericName, Qualifier.LiteralType t ) ->
            Dict.insert genericName t bindings

        ( _, Qualifier.RecursiveMatch (Qualifier.TypeMatch _ _ subConds) ) ->
            List.foldl whenConditionsGenericBindings bindings subConds

        _ ->
            bindings


whenConditionsBindGenerics : Dict String Type -> Qualifier.TypeMatchCond -> Qualifier.TypeMatchCond
whenConditionsBindGenerics bindings (Qualifier.TypeMatchCond fieldName fieldType value) =
    let
        boundValue =
            case value of
                Qualifier.LiteralType t ->
                    Qualifier.LiteralType <| bindGenericsInType bindings t

                Qualifier.RecursiveMatch (Qualifier.TypeMatch subLoc subType subConds) ->
                    Qualifier.RecursiveMatch <|
                        Qualifier.TypeMatch
                            subLoc
                            (bindGenericsInType bindings subType)
                            (List.map (whenConditionsBindGenerics bindings) subConds)

                _ ->
                    value
    in
    Qualifier.TypeMatchCond
        fieldName
        (bindGenericsInType bindings fieldType)
        boundValue



bindGenericsInType : Dict String Type -> Type -> Type
bindGenericsInType bindings t =
    case t of
        Type.Generic genericName ->
            Dict.get genericName bindings
................................................................................


inferWhenTypes :
    Qualifier.FunctionDefinition
    -> ( Qualifier.TypeMatch, List Qualifier.Node )
    -> ( List FunctionType, Context )
    -> ( List FunctionType, Context )
inferWhenTypes untypedDef ( Qualifier.TypeMatch _ t _, im ) ( infs, ctx ) =
    let



        alteredTypeSignature =
            case untypedDef.typeSignature of
                TypeSignature.UserProvided wt ->
                    TypeSignature.UserProvided <|
                        case wt.input of
                            firstAnnotatedType :: rest ->
                                { wt | input = resolveFirstType firstAnnotatedType t :: rest }
................................................................................

                            _ ->
                                wt

                x ->
                    x

















        resolveFirstType : Type -> Type -> Type
        resolveFirstType annotatedType typeMatchType =
            case ( annotatedType, typeMatchType ) of
                ( Type.Union _ unionMembers, Type.CustomGeneric name _ ) ->
                    List.find (matchingCustomGenericType name) unionMembers
                        |> Maybe.withDefault typeMatchType

                ( Type.CustomGeneric annName _, Type.CustomGeneric matchName _ ) ->
                    if annName == matchName then
                        annotatedType

                    else
                        typeMatchType

                _ ->
                    typeMatchType


        matchingCustomGenericType : String -> Type -> Bool
        matchingCustomGenericType nameToMatch tipe =
            case tipe of
                Type.CustomGeneric name _ ->
                    name == nameToMatch

                _ ->
                    False

        ( inf, newCtx ) =
            typeCheckImplementation untypedDef alteredTypeSignature im (cleanContext ctx)
    in
    ( inf :: infs, newCtx )


normalizeWhenTypes : List FunctionType -> List FunctionType
normalizeWhenTypes whenTypes =
    let
        maybeLongestInputWhenType =
            List.sortBy (.input >> List.length) whenTypes
                |> List.reverse
................................................................................
        (\wt -> Tuple.first (simplifyFunctionType ( wt, context )))
        functionTypes
    , context
    )


replaceFirstTypeWithPatternMatch : ( Qualifier.TypeMatch, FunctionType ) -> FunctionType
replaceFirstTypeWithPatternMatch ( Qualifier.TypeMatch _ matchType _, typeSignature ) =




    case typeSignature.input of
        ((Type.Generic _) as toReplace) :: _ ->
            { input = List.map (replaceType toReplace matchType) typeSignature.input
            , output = List.map (replaceType toReplace matchType) typeSignature.output
            }

        ((Type.StackRange _) as toReplace) :: _ ->
................................................................................


unionOfTypeMatches : List ( Qualifier.TypeMatch, a ) -> Type
unionOfTypeMatches whenBranches =
    let
        uniqueTypes =
            whenBranches
                |> List.map (Tuple.first >> extractTypeFromTypeMatch)
                |> List.concatMap flattenUnions
                |> List.gatherEquals
                |> List.map Tuple.first

        flattenUnions t =
            case t of
                Type.Union _ members ->
................................................................................
                (constrainedFunction :: acc)

        ( _ :: annotatedRest, inferredEl :: inferredRest ) ->
            constrainGenericsHelper remappedGenerics annotatedRest inferredRest (inferredEl :: acc)


patternMatchIsCompatibleWithInferredType : ( Qualifier.TypeMatch, FunctionType ) -> Bool
patternMatchIsCompatibleWithInferredType ( Qualifier.TypeMatch _ typeMatchType _, inf ) =
    case inf.input of
        inferredType :: _ ->
            Type.genericlyCompatible typeMatchType inferredType

        [] ->
            False


dropFirstInputType : FunctionType -> FunctionType
dropFirstInputType inf =
................................................................................
                |> Maybe.map .input
                |> Maybe.withDefault []
    in
    functionTypeFromStackEffects untypedDef contextWithStackEffects
        |> (\( ctx, wt ) -> ( { wt | input = wt.input ++ annotatedInput }, ctx ))
        |> simplifyFunctionType


extractTypeFromTypeMatch : Qualifier.TypeMatch -> Type


extractTypeFromTypeMatch (Qualifier.TypeMatch _ t_ _) =
    t_



mapTypeMatch : Qualifier.TypeMatch -> TypeMatch
mapTypeMatch (Qualifier.TypeMatch range type_ cond) =
    TypeMatch range type_ (List.map mapTypeMatchCond cond)


mapTypeMatchCond : Qualifier.TypeMatchCond -> ( String, TypeMatchValue )
mapTypeMatchCond (Qualifier.TypeMatchCond fieldName _ value) =
    case value of
        Qualifier.LiteralInt val ->
            ( fieldName, LiteralInt val )

        Qualifier.LiteralType val ->
            ( fieldName, LiteralType val )

        Qualifier.RecursiveMatch val ->
            ( fieldName, RecursiveMatch (mapTypeMatch val) )


type InexhaustiveState
    = Total
    | SeenInt


inexhaustivenessCheck : SourceLocationRange -> List Qualifier.TypeMatch -> Maybe Problem
inexhaustivenessCheck range patterns =




    let
        inexhaustiveStates =
            List.foldl (inexhaustivenessCheckHelper []) [] patterns
                |> List.filter (\( _, state ) -> state /= Total)
                |> List.map Tuple.first
    in
    case inexhaustiveStates of
        [] ->
            Nothing

        _ ->
            Just (InexhaustiveMultiFunction range inexhaustiveStates)


inexhaustivenessCheckHelper : List Type -> Qualifier.TypeMatch -> List ( List Type, InexhaustiveState ) -> List ( List Type, InexhaustiveState )
inexhaustivenessCheckHelper typePrefix (Qualifier.TypeMatch _ t conds) acc =
    let








        typeList =
            typePrefix ++ [ t ]
    in
    if List.any (\( toMatch, state ) -> typeList == toMatch && state == Total) acc then
        acc

    else
        let
            subcases =
                conds
                    |> List.filterMap isRecursiveMatch
                    |> List.foldl (inexhaustivenessCheckHelper typeList) acc

            isRecursiveMatch cond =
                case cond of
                    Qualifier.TypeMatchCond _ _ (Qualifier.RecursiveMatch val) ->
                        Just val

                    _ ->
                        Nothing

            toAdd =
                case ( t, conds, subcases ) of
                    ( _, [], _ ) ->


                        [ ( typeList, Total ) ]

                    ( Type.Int, _, _ ) ->
                        [ ( typeList, SeenInt ) ]

                    _ ->
                        if List.all (Tuple.second >> (==) Total) subcases then
                            [ ( typeList, Total ) ]

                        else







<







 







>
|
<
<
<
<
<
<







 







|


|
>
>
>







 







|







 







|
|
|







|

|







 







|
|

|


|


|






|
|



<
<
<
|
<
|
|
|
|




<
|
|
|
>







 







|

>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|

|
|
|

|
|

|
|

>
|
|
|
|
|

|
|

<
<
<
<
<







 







|
>
>
>
>







 







|







 







|


|







 








|
>
>
|
<
>

<
|
<
|


|
|
<
<
|
<
<
<
<
<
<







|
|
>
>
>
>
|
|
|
|
|
|
|
|
|

|
|



|

>
>
>
>
>
>
>
>










|


|
|
<
<

<
<
<

<
<
>
>


|







2
3
4
5
6
7
8

9
10
11
12
13
14
15
..
42
43
44
45
46
47
48
49
50






51
52
53
54
55
56
57
...
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
...
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
...
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
...
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
...
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
...
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
...
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
....
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
....
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100

1101
1102

1103

1104
1105
1106
1107
1108


1109






1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162


1163



1164


1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
    ( AST
    , AstNode(..)
    , CycleData
    , FunctionDefinition
    , FunctionImplementation(..)
    , TypeDefinition
    , TypeMatch(..)

    , run
    )

import Dict exposing (Dict)
import List.Extra as List
import Result.Extra as Result
import Set exposing (Set)
................................................................................

type FunctionImplementation
    = SoloImpl (List AstNode)
    | MultiImpl (List ( TypeMatch, List AstNode )) (List AstNode)


type TypeMatch
    = TypeMatchInt SourceLocationRange Int
    | TypeMatchType SourceLocationRange Type (List ( String, TypeMatch ))








type AstNode
    = IntLiteral SourceLocationRange Int
    | ArrayLiteral SourceLocationRange (List AstNode) Type
    | Function SourceLocationRange FunctionDefinition FunctionType
    | FunctionRef SourceLocationRange FunctionDefinition
................................................................................
                                untypedDef
                                untypedDef.typeSignature
                                defaultImpl
                                (cleanContext context)
                    in
                    case inferredDefaultType.input of
                        [] ->
                            ( Qualifier.TypeMatchType SourceLocation.emptyRange (Type.Generic "*") [], defaultImpl ) :: initialWhens

                        firstType :: _ ->
                            ( Qualifier.TypeMatchType SourceLocation.emptyRange firstType [], defaultImpl ) :: initialWhens

        hasDefaultBranch =
            not <| List.isEmpty defaultImpl

        whens =
            List.map (Tuple.mapFirst (resolveWhenConditions untypedDef)) allBranches

        ( inferredWhenTypes, newContext ) =
            whens
                |> List.foldr (inferWhenTypes untypedDef) ( [], context )
................................................................................
            if whensAreConsistent && whensAreCompatible then
                Nothing

            else
                Just <| InconsistentWhens sourceLocation untypedDef.name

        maybeInexhaustiveError =
            inexhaustivenessCheck sourceLocation hasDefaultBranch whenPatterns

        sourceLocation =
            Maybe.withDefault SourceLocation.emptyRange untypedDef.sourceLocation

        typedDef =
            { name = untypedDef.name
            , sourceLocation = untypedDef.sourceLocation
................................................................................
    in
    ( typedDef
    , finalContext
    )


resolveWhenConditions : Qualifier.FunctionDefinition -> Qualifier.TypeMatch -> Qualifier.TypeMatch
resolveWhenConditions untypedDef match =
    case match of
        Qualifier.TypeMatchType loc ((Type.CustomGeneric _ structGenerics) as t) conds ->
            let
                bindings =
                    List.foldl
                        whenConditionsGenericBindings
                        (initialBindingsFromFunctionDef untypedDef structGenerics)
                        conds
            in
            Qualifier.TypeMatchType
                loc
                (bindGenericsInType bindings t)
                (List.map (whenConditionsBindGenerics bindings) conds)

        _ ->
            match


initialBindingsFromFunctionDef : Qualifier.FunctionDefinition -> List Type -> Dict String Type
................................................................................
                _ ->
                    Dict.empty

        Nothing ->
            Dict.empty


whenConditionsGenericBindings : ( String, Type, Qualifier.TypeMatch ) -> Dict String Type -> Dict String Type
whenConditionsGenericBindings ( _, fieldType, value ) bindings =
    case ( fieldType, value ) of
        ( Type.Generic genericName, Qualifier.TypeMatchInt _ _ ) ->
            Dict.insert genericName Type.Int bindings

        ( Type.Generic genericName, Qualifier.TypeMatchType _ t [] ) ->
            Dict.insert genericName t bindings

        ( _, Qualifier.TypeMatchType _ _ subConds ) ->
            List.foldl whenConditionsGenericBindings bindings subConds

        _ ->
            bindings


whenConditionsBindGenerics : Dict String Type -> ( String, Type, Qualifier.TypeMatch ) -> ( String, Type, Qualifier.TypeMatch )
whenConditionsBindGenerics bindings ( fieldName, fieldType, value ) =
    let
        boundValue =
            case value of



                Qualifier.TypeMatchType subLoc subType subConds ->

                    Qualifier.TypeMatchType
                        subLoc
                        (bindGenericsInType bindings subType)
                        (List.map (whenConditionsBindGenerics bindings) subConds)

                _ ->
                    value
    in

    ( fieldName
    , bindGenericsInType bindings fieldType
    , boundValue
    )


bindGenericsInType : Dict String Type -> Type -> Type
bindGenericsInType bindings t =
    case t of
        Type.Generic genericName ->
            Dict.get genericName bindings
................................................................................


inferWhenTypes :
    Qualifier.FunctionDefinition
    -> ( Qualifier.TypeMatch, List Qualifier.Node )
    -> ( List FunctionType, Context )
    -> ( List FunctionType, Context )
inferWhenTypes untypedDef ( typeMatch, im ) ( infs, ctx ) =
    let
        t =
            typeOfTypeMatch typeMatch

        alteredTypeSignature =
            case untypedDef.typeSignature of
                TypeSignature.UserProvided wt ->
                    TypeSignature.UserProvided <|
                        case wt.input of
                            firstAnnotatedType :: rest ->
                                { wt | input = resolveFirstType firstAnnotatedType t :: rest }
................................................................................

                            _ ->
                                wt

                x ->
                    x

        ( inf, newCtx ) =
            typeCheckImplementation untypedDef alteredTypeSignature im (cleanContext ctx)
    in
    ( inf :: infs, newCtx )


typeOfTypeMatch : Qualifier.TypeMatch -> Type
typeOfTypeMatch typeMatch =
    case typeMatch of
        Qualifier.TypeMatchInt _ _ ->
            Type.Int

        Qualifier.TypeMatchType _ t _ ->
            t


resolveFirstType : Type -> Type -> Type
resolveFirstType annotatedType typeMatchType =
    case ( annotatedType, typeMatchType ) of
        ( Type.Union _ unionMembers, Type.CustomGeneric name _ ) ->
            List.find (matchingCustomGenericType name) unionMembers
                |> Maybe.withDefault typeMatchType

        ( Type.CustomGeneric annName _, Type.CustomGeneric matchName _ ) ->
            if annName == matchName then
                annotatedType

            else
                typeMatchType

        _ ->
            typeMatchType


matchingCustomGenericType : String -> Type -> Bool
matchingCustomGenericType nameToMatch tipe =
    case tipe of
        Type.CustomGeneric name _ ->
            name == nameToMatch

        _ ->
            False







normalizeWhenTypes : List FunctionType -> List FunctionType
normalizeWhenTypes whenTypes =
    let
        maybeLongestInputWhenType =
            List.sortBy (.input >> List.length) whenTypes
                |> List.reverse
................................................................................
        (\wt -> Tuple.first (simplifyFunctionType ( wt, context )))
        functionTypes
    , context
    )


replaceFirstTypeWithPatternMatch : ( Qualifier.TypeMatch, FunctionType ) -> FunctionType
replaceFirstTypeWithPatternMatch ( typeMatch, typeSignature ) =
    let
        matchType =
            typeOfTypeMatch typeMatch
    in
    case typeSignature.input of
        ((Type.Generic _) as toReplace) :: _ ->
            { input = List.map (replaceType toReplace matchType) typeSignature.input
            , output = List.map (replaceType toReplace matchType) typeSignature.output
            }

        ((Type.StackRange _) as toReplace) :: _ ->
................................................................................


unionOfTypeMatches : List ( Qualifier.TypeMatch, a ) -> Type
unionOfTypeMatches whenBranches =
    let
        uniqueTypes =
            whenBranches
                |> List.map (Tuple.first >> typeOfTypeMatch)
                |> List.concatMap flattenUnions
                |> List.gatherEquals
                |> List.map Tuple.first

        flattenUnions t =
            case t of
                Type.Union _ members ->
................................................................................
                (constrainedFunction :: acc)

        ( _ :: annotatedRest, inferredEl :: inferredRest ) ->
            constrainGenericsHelper remappedGenerics annotatedRest inferredRest (inferredEl :: acc)


patternMatchIsCompatibleWithInferredType : ( Qualifier.TypeMatch, FunctionType ) -> Bool
patternMatchIsCompatibleWithInferredType ( typeMatch, inf ) =
    case inf.input of
        inferredType :: _ ->
            Type.genericlyCompatible (typeOfTypeMatch typeMatch) inferredType

        [] ->
            False


dropFirstInputType : FunctionType -> FunctionType
dropFirstInputType inf =
................................................................................
                |> Maybe.map .input
                |> Maybe.withDefault []
    in
    functionTypeFromStackEffects untypedDef contextWithStackEffects
        |> (\( ctx, wt ) -> ( { wt | input = wt.input ++ annotatedInput }, ctx ))
        |> simplifyFunctionType


mapTypeMatch : Qualifier.TypeMatch -> TypeMatch
mapTypeMatch typeMatch =
    case typeMatch of
        Qualifier.TypeMatchInt range val ->

            TypeMatchInt range val


        Qualifier.TypeMatchType range type_ cond ->

            TypeMatchType range type_ (List.map (mapQualifiedMatch mapTypeMatch) cond)


mapQualifiedMatch : (Qualifier.TypeMatch -> TypeMatch) -> ( String, Type, Qualifier.TypeMatch ) -> ( String, TypeMatch )
mapQualifiedMatch fn ( fieldName, _, match ) =


    ( fieldName, fn match )








type InexhaustiveState
    = Total
    | SeenInt


inexhaustivenessCheck : SourceLocationRange -> Bool -> List Qualifier.TypeMatch -> Maybe Problem
inexhaustivenessCheck range hasDefaultBranch patterns =
    if hasDefaultBranch then
        Nothing

    else
        let
            inexhaustiveStates =
                List.foldl (inexhaustivenessCheckHelper []) [] patterns
                    |> List.filter (\( _, state ) -> state /= Total)
                    |> List.map Tuple.first
        in
        case inexhaustiveStates of
            [] ->
                Nothing

            _ ->
                Just (InexhaustiveMultiFunction range inexhaustiveStates)


inexhaustivenessCheckHelper : List Type -> Qualifier.TypeMatch -> List ( List Type, InexhaustiveState ) -> List ( List Type, InexhaustiveState )
inexhaustivenessCheckHelper typePrefix typeMatch acc =
    let
        ( t, intLiteral, conds ) =
            case typeMatch of
                Qualifier.TypeMatchInt _ _ ->
                    ( Type.Int, True, [] )

                Qualifier.TypeMatchType _ t_ conds_ ->
                    ( t_, False, conds_ )

        typeList =
            typePrefix ++ [ t ]
    in
    if List.any (\( toMatch, state ) -> typeList == toMatch && state == Total) acc then
        acc

    else
        let
            subcases =
                conds
                    |> List.map isRecursiveMatch
                    |> List.foldl (inexhaustivenessCheckHelper typeList) acc

            isRecursiveMatch ( _, _, match ) =
                match






            toAdd =


                case ( t, intLiteral, conds ) of
                    ( _, False, [] ) ->
                        [ ( typeList, Total ) ]

                    ( Type.Int, True, [] ) ->
                        [ ( typeList, SeenInt ) ]

                    _ ->
                        if List.all (Tuple.second >> (==) Total) subcases then
                            [ ( typeList, Total ) ]

                        else

Modified tests/Test/Parser.elm from [b630228d82] to [e6646f0f1b].

519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
...
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
...
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
...
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
...
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
...
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
...
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
....
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031

1032
1033
1034
1035
1036
1037
1038
1039
1040
....
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
....
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
....
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272

1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
....
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (LocalRef "True" []) []
                                                  , [ AST.Function emptyRange "drop", AST.Integer emptyRange 1 ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "False" []) []
                                                  , [ AST.Function emptyRange "drop", AST.Integer emptyRange 0 ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = "Converts a boolean into an int"
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (LocalRef "True" []) []
                                                  , [ AST.Function emptyRange "drop", AST.Integer emptyRange 1 ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "False" []) []
                                                  , [ AST.Function emptyRange "drop", AST.Integer emptyRange 0 ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Generic "a") []
                                                  , [ AST.Function emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Function emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (LocalRef "Box" [ Generic "a" ]) []
                                                  , [ AST.Function emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Function emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                                                }
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (LocalRef "Box" [ Generic "a" ]) []
                                                  , [ AST.Function emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Function emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
        , describe "Pattern matching"
            [ test "Single match" <|
                \_ ->
                    let
                        source =
                            """
                            defmulti: zero?
                            : Int( value 0 )
                              True
                            else: False
                            """

                        expectedAst =
                            { sourceReference = ""
                            , moduleDefinition = ModuleDefinition.Undefined
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch
                                                        emptyRange
                                                        (LocalRef "Int" [])
                                                        [ ( "value", AST.LiteralInt 0 )
                                                        ]
                                                  , [ AST.Function emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Function emptyRange "False" ]
                                      }
                                    ]
                            }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange
                                                        (LocalRef "List" [])
                                                        [ ( "tail"
                                                          , AST.RecursiveMatch
                                                                (TypeMatch emptyRange
                                                                    (LocalRef "List" [])
                                                                    [ ( "tail", AST.LiteralType (LocalRef "Nil" []) )

                                                                    ]
                                                                )
                                                          )
                                                        ]
                                                  , [ AST.Function emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Function emptyRange "False" ]
                                      }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange
                                                        (LocalRef "Pair" [])
                                                        [ ( "first", AST.LiteralInt 0 )
                                                        , ( "second", AST.LiteralInt 0 )
                                                        ]
                                                  , [ AST.Function emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Function emptyRange "False" ]
                                      }
                                    ]
................................................................................
                        : False

                        defstruct: True
                        defstruct: False

                        defmulti: from-int
                        type: Int -- Int
                        : Int( value 0 )
                          False>
                        : Int
                          True>

                        def: equal
                        : - from-int not

................................................................................
                                                (SourceLocation 16 1)
                                            )
                                  , documentation = ""
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 11 3)
                                                        (SourceLocation 11 17)
                                                    )
                                                    (LocalRef "Int" [])
                                                    [ ( "value", LiteralInt 0 ) ]

                                              , [ Function
                                                    (SourceLocationRange
                                                        (SourceLocation 12 3)
                                                        (SourceLocation 12 9)
                                                    )
                                                    "False>"
                                                ]
                                              )
                                            , ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 13 3)
                                                        (SourceLocation 13 6)
                                                    )
                                                    (LocalRef "Int" [])
                                                    []
                                              , [ Function
................................................................................
                                                (SourceLocation 23 1)
                                            )
                                  , documentation = ""
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 20 3)
                                                        (SourceLocation 20 7)
                                                    )
                                                    (LocalRef "True" [])
                                                    []
                                              , [ Function







|


|







 







|


|







 







|


|







 







|


|







 







|


|







 







|







 







|
<
<
<
<







 







|


<
|
|
<
>
|
<







 







|

|
|







 







|







 







|


|

<
<
>








|







 







|







519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
...
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
...
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
...
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
...
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
...
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
...
979
980
981
982
983
984
985
986




987
988
989
990
991
992
993
....
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023

1024
1025

1026
1027

1028
1029
1030
1031
1032
1033
1034
....
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
....
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
....
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264


1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
....
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatchType emptyRange (LocalRef "True" []) []
                                                  , [ AST.Function emptyRange "drop", AST.Integer emptyRange 1 ]
                                                  )
                                                , ( TypeMatchType emptyRange (LocalRef "False" []) []
                                                  , [ AST.Function emptyRange "drop", AST.Integer emptyRange 0 ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = "Converts a boolean into an int"
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatchType emptyRange (LocalRef "True" []) []
                                                  , [ AST.Function emptyRange "drop", AST.Integer emptyRange 1 ]
                                                  )
                                                , ( TypeMatchType emptyRange (LocalRef "False" []) []
                                                  , [ AST.Function emptyRange "drop", AST.Integer emptyRange 0 ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatchType emptyRange (Generic "a") []
                                                  , [ AST.Function emptyRange "!" ]
                                                  )
                                                , ( TypeMatchType emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Function emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatchType emptyRange (LocalRef "Box" [ Generic "a" ]) []
                                                  , [ AST.Function emptyRange "!" ]
                                                  )
                                                , ( TypeMatchType emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Function emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                                                }
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatchType emptyRange (LocalRef "Box" [ Generic "a" ]) []
                                                  , [ AST.Function emptyRange "!" ]
                                                  )
                                                , ( TypeMatchType emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Function emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
        , describe "Pattern matching"
            [ test "Single match" <|
                \_ ->
                    let
                        source =
                            """
                            defmulti: zero?
                            : 0
                              True
                            else: False
                            """

                        expectedAst =
                            { sourceReference = ""
                            , moduleDefinition = ModuleDefinition.Undefined
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatchInt emptyRange 0




                                                  , [ AST.Function emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Function emptyRange "False" ]
                                      }
                                    ]
                            }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatchType emptyRange
                                                        (LocalRef "List" [])
                                                        [ ( "tail"

                                                          , TypeMatchType emptyRange
                                                                (LocalRef "List" [])

                                                                [ ( "tail", TypeMatchType emptyRange (LocalRef "Nil" []) [] )
                                                                ]

                                                          )
                                                        ]
                                                  , [ AST.Function emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Function emptyRange "False" ]
                                      }
................................................................................
                                      , typeSignature = AssociatedFunctionSignature.NotProvided
                                      , sourceLocationRange = Nothing
                                      , documentation = ""
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatchType emptyRange
                                                        (LocalRef "Pair" [])
                                                        [ ( "first", TypeMatchInt emptyRange 0 )
                                                        , ( "second", TypeMatchInt emptyRange 0 )
                                                        ]
                                                  , [ AST.Function emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Function emptyRange "False" ]
                                      }
                                    ]
................................................................................
                        : False

                        defstruct: True
                        defstruct: False

                        defmulti: from-int
                        type: Int -- Int
                        : 0
                          False>
                        : Int
                          True>

                        def: equal
                        : - from-int not

................................................................................
                                                (SourceLocation 16 1)
                                            )
                                  , documentation = ""
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatchInt
                                                    (SourceLocationRange
                                                        (SourceLocation 11 3)
                                                        (SourceLocation 12 1)
                                                    )


                                                    0
                                              , [ Function
                                                    (SourceLocationRange
                                                        (SourceLocation 12 3)
                                                        (SourceLocation 12 9)
                                                    )
                                                    "False>"
                                                ]
                                              )
                                            , ( TypeMatchType
                                                    (SourceLocationRange
                                                        (SourceLocation 13 3)
                                                        (SourceLocation 13 6)
                                                    )
                                                    (LocalRef "Int" [])
                                                    []
                                              , [ Function
................................................................................
                                                (SourceLocation 23 1)
                                            )
                                  , documentation = ""
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatchType
                                                    (SourceLocationRange
                                                        (SourceLocation 20 3)
                                                        (SourceLocation 20 7)
                                                    )
                                                    (LocalRef "True" [])
                                                    []
                                              , [ Function

Modified tests/Test/Parser/ModuleDefinition.elm from [598f9224a4] to [df351f0b8c].

265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
                                        Dict.fromList
                                            [ ( "/some/other/mod", [ "test1", "word2" ] )
                                            , ( "internals", [ "foo" ] )
                                            , ( "internal/mod", [] )
                                            ]
                                  , implementation =
                                        MultiImpl
                                            [ ( AST.TypeMatch emptyRange (Generic "a") []
                                              , [ AST.Function emptyRange "drop" ]
                                              )
                                            ]
                                            [ AST.Function emptyRange "swap"
                                            , AST.Function emptyRange "drop"
                                            ]
                                  }







|







265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
                                        Dict.fromList
                                            [ ( "/some/other/mod", [ "test1", "word2" ] )
                                            , ( "internals", [ "foo" ] )
                                            , ( "internal/mod", [] )
                                            ]
                                  , implementation =
                                        MultiImpl
                                            [ ( AST.TypeMatchType emptyRange (Generic "a") []
                                              , [ AST.Function emptyRange "drop" ]
                                              )
                                            ]
                                            [ AST.Function emptyRange "swap"
                                            , AST.Function emptyRange "drop"
                                            ]
                                  }

Modified tests/Test/Parser/QualifiedRefs.elm from [6b5fcdd2e5] to [b5b2da8cf8].

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
...
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
                                            }
                                  , sourceLocationRange = Nothing
                                  , documentation = ""
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatch emptyRange (ExternalRef [ "external" ] "Tipe" []) [ ( "value", LiteralInt 1 ) ]
                                              , [ AST.Function emptyRange "drop"
                                                , AST.Integer emptyRange 1
                                                ]
                                              )
                                            ]
                                            [ AST.Function emptyRange "drop"
                                            , AST.Integer emptyRange 0
................................................................................
                                            }
                                  , sourceLocationRange = Nothing
                                  , documentation = ""
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatch emptyRange (InternalRef [ "internal" ] "Tipe" []) [ ( "value", LiteralInt 1 ) ]
                                              , [ AST.Function emptyRange "drop"
                                                , AST.Integer emptyRange 1
                                                ]
                                              )
                                            ]
                                            [ AST.Function emptyRange "drop"
                                            , AST.Integer emptyRange 0







|







 







|







202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
...
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
                                            }
                                  , sourceLocationRange = Nothing
                                  , documentation = ""
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatchType emptyRange (ExternalRef [ "external" ] "Tipe" []) [ ( "value", TypeMatchInt emptyRange 1 ) ]
                                              , [ AST.Function emptyRange "drop"
                                                , AST.Integer emptyRange 1
                                                ]
                                              )
                                            ]
                                            [ AST.Function emptyRange "drop"
                                            , AST.Integer emptyRange 0
................................................................................
                                            }
                                  , sourceLocationRange = Nothing
                                  , documentation = ""
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatchType emptyRange (InternalRef [ "internal" ] "Tipe" []) [ ( "value", TypeMatchInt emptyRange 1 ) ]
                                              , [ AST.Function emptyRange "drop"
                                                , AST.Integer emptyRange 1
                                                ]
                                              )
                                            ]
                                            [ AST.Function emptyRange "drop"
                                            , AST.Integer emptyRange 0

Modified tests/Test/Parser/Util.elm from [0c312f5c79] to [d2ff50d105].

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
stripMultiWordBranchLocation ( typeMatch, nodes ) =
    ( stripTypeMatchLocation typeMatch
    , List.map stripNodeLocation nodes
    )


stripTypeMatchLocation : TypeMatch -> TypeMatch
stripTypeMatchLocation (TypeMatch _ type_ otherConds) =
    TypeMatch emptyRange type_ <|
        List.map (Tuple.mapSecond stripRecursiveTypeMatchLocation) otherConds



stripRecursiveTypeMatchLocation : TypeMatchValue -> TypeMatchValue
stripRecursiveTypeMatchLocation typeMatchValue =
    case typeMatchValue of
        RecursiveMatch typeMatch ->
            RecursiveMatch (stripTypeMatchLocation typeMatch)

        _ ->
            typeMatchValue


addFunctionsForStructs : AST -> AST
addFunctionsForStructs ast =
    let
        helper _ t wipAst =
            case t.members of







|
|
|
>

<
|
|
<
<
|
<
<
<







96
97
98
99
100
101
102
103
104
105
106
107

108
109


110



111
112
113
114
115
116
117
stripMultiWordBranchLocation ( typeMatch, nodes ) =
    ( stripTypeMatchLocation typeMatch
    , List.map stripNodeLocation nodes
    )


stripTypeMatchLocation : TypeMatch -> TypeMatch
stripTypeMatchLocation match =
    case match of
        TypeMatchInt _ int ->
            TypeMatchInt emptyRange int


        TypeMatchType _ type_ otherConds ->
            TypeMatchType emptyRange type_ <|


                List.map (Tuple.mapSecond stripTypeMatchLocation) otherConds





addFunctionsForStructs : AST -> AST
addFunctionsForStructs ast =
    let
        helper _ t wipAst =
            case t.members of

Modified tests/Test/Qualifier.elm from [5a6565cefb] to [eb2f930745].

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
...
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    describe "Qualifier"
        [ test "Recursive function" <|
            \_ ->
                let
                    source =
                        """
                        defmulti: count-down
                        : Int( value 0 )
                          0

                        : Int
                          1 - count-down
                        """
                in
                QualifierUtil.expectQualification source
        , test "Recursive function through inline function" <|
            \_ ->
                let
                    source =
                        """
                        defmulti: count-down
                        : Int( value 0 )
                          0

                        : Int
                          [ count-down ] !
                        """
                in
                QualifierUtil.expectQualification source
        , test "Function cycle" <|
            \_ ->
................................................................................
                let
                    source =
                        """
                        def: dec-down
                        : 1 - count-down 

                        defmulti: count-down
                        : Int( value 0 )
                          0

                        : Int
                          dec-down
                        """
                in
                QualifierUtil.expectQualification source
        , test "Function cycle with inline function" <|
            \_ ->
................................................................................
                let
                    source =
                        """
                        def: dec-down
                        : 1 - count-down 

                        defmulti: count-down
                        : Int( value 0 )
                          0

                        : Int
                          [ dec-down ] !
                        """
                in
                QualifierUtil.expectQualification source
        , test "Name mangling" <|
            \_ ->
................................................................................
                        , typeSignature =
                            TypeSignature.UserProvided
                                { input = [ usMoneyUnionType ]
                                , output = [ Type.Int ]
                                }
                        , implementation =
                            MultiImpl
                                [ ( TypeMatch emptyRange (Type.Custom "/stabel/test/some/module/Dollar") []
                                  , [ Function emptyRange dollarValueGetFn
                                    , Integer emptyRange 100
                                    , Builtin emptyRange Builtin.Multiply
                                    ]
                                  )
                                , ( TypeMatch emptyRange (Type.Custom "/stabel/test/some/module/Cent") []
                                  , [ Function emptyRange centValueGetFn
                                    ]
                                  )
                                ]
                                []
                        }








|
<
>











|
<
>







 







|
<
>







 







|
<
>







 







|





|







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
...
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    describe "Qualifier"
        [ test "Recursive function" <|
            \_ ->
                let
                    source =
                        """
                        defmulti: count-down
                        : 0

                          drop 0
                        : Int
                          1 - count-down
                        """
                in
                QualifierUtil.expectQualification source
        , test "Recursive function through inline function" <|
            \_ ->
                let
                    source =
                        """
                        defmulti: count-down
                        : 0

                          drop 0
                        : Int
                          [ count-down ] !
                        """
                in
                QualifierUtil.expectQualification source
        , test "Function cycle" <|
            \_ ->
................................................................................
                let
                    source =
                        """
                        def: dec-down
                        : 1 - count-down 

                        defmulti: count-down
                        : 0

                          drop 0
                        : Int
                          dec-down
                        """
                in
                QualifierUtil.expectQualification source
        , test "Function cycle with inline function" <|
            \_ ->
................................................................................
                let
                    source =
                        """
                        def: dec-down
                        : 1 - count-down 

                        defmulti: count-down
                        : 0

                          drop 0
                        : Int
                          [ dec-down ] !
                        """
                in
                QualifierUtil.expectQualification source
        , test "Name mangling" <|
            \_ ->
................................................................................
                        , typeSignature =
                            TypeSignature.UserProvided
                                { input = [ usMoneyUnionType ]
                                , output = [ Type.Int ]
                                }
                        , implementation =
                            MultiImpl
                                [ ( TypeMatchType emptyRange (Type.Custom "/stabel/test/some/module/Dollar") []
                                  , [ Function emptyRange dollarValueGetFn
                                    , Integer emptyRange 100
                                    , Builtin emptyRange Builtin.Multiply
                                    ]
                                  )
                                , ( TypeMatchType emptyRange (Type.Custom "/stabel/test/some/module/Cent") []
                                  , [ Function emptyRange centValueGetFn
                                    ]
                                  )
                                ]
                                []
                        }

Modified tests/Test/Qualifier/Util.elm from [8fae3ca458] to [f6240479a5].

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
...
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
    , stripLocations
    )

import Dict
import Expect exposing (Expectation)
import Set
import Stabel.Data.SourceLocation exposing (emptyRange)

import Stabel.Parser as Parser
import Stabel.Qualifier as AST
    exposing
        ( AST
        , FunctionDefinition
        , FunctionImplementation(..)
        , Node
        , TypeDefinition
        , TypeMatch(..)
        , TypeMatchCond(..)
        , TypeMatchValue(..)
        )


emptyAst : AST
emptyAst =
    { types = Dict.empty
    , functions = Dict.empty
................................................................................
stripMultiWordBranchLocation ( typeMatch, nodes ) =
    ( stripTypeMatchLocation typeMatch
    , List.map stripNodeLocation nodes
    )


stripTypeMatchLocation : TypeMatch -> TypeMatch
stripTypeMatchLocation (TypeMatch _ type_ otherConds) =
    TypeMatch emptyRange type_ <|
        List.map (mapTypeMatchCondValue stripRecursiveTypeMatchLocation) otherConds



mapTypeMatchCondValue : (TypeMatchValue -> TypeMatchValue) -> TypeMatchCond -> TypeMatchCond
mapTypeMatchCondValue fn (TypeMatchCond name tipe val) =
    TypeMatchCond name tipe (fn val)


stripRecursiveTypeMatchLocation : TypeMatchValue -> TypeMatchValue
stripRecursiveTypeMatchLocation typeMatchValue =
    case typeMatchValue of
        RecursiveMatch typeMatch ->
            RecursiveMatch (stripTypeMatchLocation typeMatch)

        _ ->
            typeMatchValue







>









<
<







 







|
|
|
>

<
|
|
|


|
|
<
<
|
<
<
<
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21


22
23
24
25
26
27
28
...
157
158
159
160
161
162
163
164
165
166
167
168

169
170
171
172
173
174
175


176



    , stripLocations
    )

import Dict
import Expect exposing (Expectation)
import Set
import Stabel.Data.SourceLocation exposing (emptyRange)
import Stabel.Data.Type as Type exposing (Type)
import Stabel.Parser as Parser
import Stabel.Qualifier as AST
    exposing
        ( AST
        , FunctionDefinition
        , FunctionImplementation(..)
        , Node
        , TypeDefinition
        , TypeMatch(..)


        )


emptyAst : AST
emptyAst =
    { types = Dict.empty
    , functions = Dict.empty
................................................................................
stripMultiWordBranchLocation ( typeMatch, nodes ) =
    ( stripTypeMatchLocation typeMatch
    , List.map stripNodeLocation nodes
    )


stripTypeMatchLocation : TypeMatch -> TypeMatch
stripTypeMatchLocation typeMatch =
    case typeMatch of
        TypeMatchInt _ val ->
            TypeMatchInt emptyRange val


        TypeMatchType _ type_ otherConds ->
            TypeMatchType emptyRange type_ <|
                List.map stripTypeMatchCondLocation otherConds


stripTypeMatchCondLocation : ( String, Type, TypeMatch ) -> ( String, Type, TypeMatch )
stripTypeMatchCondLocation ( fieldName, fieldType, match ) =


    ( fieldName, fieldType, stripTypeMatchLocation match )



Modified tests/Test/TypeChecker/Errors.elm from [46be466d12] to [92b4c5c362].

211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
...
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
...
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
...
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
...
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
...
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
...
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406

                        def: main
                        type: -- out
                        : 0 true-or-false

                        defmulti: true-or-false
                        type: Int -- (Tmp a b)
                        : Int( value 0 )
                          drop False>
                        : Int
                          drop True>
                        """
                in
                Expect.equalLists
                    [ Problem.TypeError emptyRange
................................................................................

                        defstruct: True
                        defstruct: False

                        defmulti: true-or-false
                        # should be Int -- Int (Maybe a)
                        type: Int -- Int
                        : Int( value 0 )
                          False>
                        : Int
                          True>
                        """
                in
                Expect.equalLists
                    [ Problem.TypeError emptyRange
................................................................................
                    let
                        input =
                            """
                            def: main
                            : 2 mword

                            defmulti: mword
                            : Int( value 1 )
                              1 +
                            """

                        inexhaustiveError problem =
                            case problem of
                                Problem.InexhaustiveMultiFunction _ [ [ Type.Int ] ] ->
                                    True
................................................................................
                    let
                        input =
                            """
                            def: main
                            : 2 mword

                            defmulti: mword
                            : Int( value 1 )
                              1 +
                            else: 
                              0 +
                            """
                    in
                    Util.expectTypeCheck input
            , test "Nested" <|
................................................................................
                            : value Int

                            def: main
                            type: -- Int
                            : 1 >IntBox mword value>

                            defmulti: mword
                            : IntBox( value Int( value 1 ) )
                              value> 1 + >IntBox
                            """

                        inexhaustiveError problem =
                            case problem of
                                Problem.InexhaustiveMultiFunction _ [ [ Type.Custom "IntBox", Type.Int ] ] ->
                                    True

                                _ ->
                                    False
                    in
                    checkForError inexhaustiveError input



















            , test "A total branch should remove any earlier seen branch" <|
                \_ ->
                    let
                        input =
                            """
                            def: main
                            : 2 mword

                            defmulti: mword
                            : Int( value 1 )
                              1 +
                            : Int
                              dup +
                            """
                    in
                    Util.expectTypeCheck input
            , test "A total branch should prevent addition of later partial branch" <|
................................................................................
                            """
                            def: main
                            : 2 mword

                            defmulti: mword
                            : Int
                              dup +
                            : Int( value 1 )
                              1 +
                            """
                    in
                    Util.expectTypeCheck input
            , test "Test with non-int type as pattern" <|
                \_ ->
                    let
................................................................................
                            defstruct: IntBox
                            : value Int

                            defstruct: Nil

                            defmulti: with-default
                            type: (Maybe IntBox) Int -- Int
                            : IntBox( value Int( value 0 ) )
                              drop value>
                            : Nil
                              swap drop

                            def: main
                            : Nil> 1 with-default
                            """







|







 







|







 







|







 







|







 







|












>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>









|







 







|







 







|







211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
...
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
...
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
...
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
...
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
...
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
...
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425

                        def: main
                        type: -- out
                        : 0 true-or-false

                        defmulti: true-or-false
                        type: Int -- (Tmp a b)
                        : 0
                          drop False>
                        : Int
                          drop True>
                        """
                in
                Expect.equalLists
                    [ Problem.TypeError emptyRange
................................................................................

                        defstruct: True
                        defstruct: False

                        defmulti: true-or-false
                        # should be Int -- Int (Maybe a)
                        type: Int -- Int
                        : 0
                          False>
                        : Int
                          True>
                        """
                in
                Expect.equalLists
                    [ Problem.TypeError emptyRange
................................................................................
                    let
                        input =
                            """
                            def: main
                            : 2 mword

                            defmulti: mword
                            : 1
                              1 +
                            """

                        inexhaustiveError problem =
                            case problem of
                                Problem.InexhaustiveMultiFunction _ [ [ Type.Int ] ] ->
                                    True
................................................................................
                    let
                        input =
                            """
                            def: main
                            : 2 mword

                            defmulti: mword
                            : 1
                              1 +
                            else: 
                              0 +
                            """
                    in
                    Util.expectTypeCheck input
            , test "Nested" <|
................................................................................
                            : value Int

                            def: main
                            type: -- Int
                            : 1 >IntBox mword value>

                            defmulti: mword
                            : IntBox( value 1 )
                              value> 1 + >IntBox
                            """

                        inexhaustiveError problem =
                            case problem of
                                Problem.InexhaustiveMultiFunction _ [ [ Type.Custom "IntBox", Type.Int ] ] ->
                                    True

                                _ ->
                                    False
                    in
                    checkForError inexhaustiveError input
            , test "Default clause is exhaustive in case of nested match" <|
                \_ ->
                    let
                        input =
                            """
                            defstruct: Box
                            : value Int

                            def: main
                            : 2 >Box mword

                            defmulti: mword
                            : Box( value 1 )
                              drop 1
                            else: 
                              drop 0
                            """
                    in
                    Util.expectTypeCheck input
            , test "A total branch should remove any earlier seen branch" <|
                \_ ->
                    let
                        input =
                            """
                            def: main
                            : 2 mword

                            defmulti: mword
                            : 1
                              1 +
                            : Int
                              dup +
                            """
                    in
                    Util.expectTypeCheck input
            , test "A total branch should prevent addition of later partial branch" <|
................................................................................
                            """
                            def: main
                            : 2 mword

                            defmulti: mword
                            : Int
                              dup +
                            : 1
                              1 +
                            """
                    in
                    Util.expectTypeCheck input
            , test "Test with non-int type as pattern" <|
                \_ ->
                    let
................................................................................
                            defstruct: IntBox
                            : value Int

                            defstruct: Nil

                            defmulti: with-default
                            type: (Maybe IntBox) Int -- Int
                            : IntBox( value 0 )
                              drop value>
                            : Nil
                              swap drop

                            def: main
                            : Nil> 1 with-default
                            """

Modified tests/Test/TypeChecker/Unions.elm from [9955d381cb] to [9a884413e9].

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
                                , Type.Generic "a"
                                ]
                            , output = [ Type.Generic "a" ]
                            }
                        , sourceLocation = Nothing
                        , implementation =
                            MultiImpl
                                [ ( TypeMatch emptyRange (Type.Generic "a") []
                                  , [ Builtin emptyRange Builtin.StackDrop
                                    ]
                                  )
                                , ( TypeMatch emptyRange (Type.Custom "Nil") []
                                  , [ Builtin emptyRange Builtin.StackSwap
                                    , Builtin emptyRange Builtin.StackDrop
                                    ]
                                  )
                                ]
                                []
                        }







|



|







218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
                                , Type.Generic "a"
                                ]
                            , output = [ Type.Generic "a" ]
                            }
                        , sourceLocation = Nothing
                        , implementation =
                            MultiImpl
                                [ ( TypeMatchType emptyRange (Type.Generic "a") []
                                  , [ Builtin emptyRange Builtin.StackDrop
                                    ]
                                  )
                                , ( TypeMatchType emptyRange (Type.Custom "Nil") []
                                  , [ Builtin emptyRange Builtin.StackSwap
                                    , Builtin emptyRange Builtin.StackDrop
                                    ]
                                  )
                                ]
                                []
                        }

Modified wasm_tests/module_resolution.test.js from [327530c16f] to [b4cd6fda72].

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
...
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
                module: 'internal',
                source: `
                    def: inc
                    : 1 +

                    defmulti: flip
                    type: Int -- Int
                    : Int( value 1 )
                      drop 0
                    else: drop 1
                `
            },
            {
                package: 'author/sample',
                module: 'core',
................................................................................
                module: 'external',
                source: `
                    def: inc
                    : 1 +

                    defmulti: flip
                    type: Int -- Int
                    : Int( value 1 )
                      drop 0
                    else: drop 1
                `
            },
            {
                package: 'author/sample',
                module: 'core',







|







 







|







10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
...
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
                module: 'internal',
                source: `
                    def: inc
                    : 1 +

                    defmulti: flip
                    type: Int -- Int
                    : 1
                      drop 0
                    else: drop 1
                `
            },
            {
                package: 'author/sample',
                module: 'core',
................................................................................
                module: 'external',
                source: `
                    def: inc
                    : 1 +

                    defmulti: flip
                    type: Int -- Int
                    : 1
                      drop 0
                    else: drop 1
                `
            },
            {
                package: 'author/sample',
                module: 'core',

Modified wasm_tests/multifunctions.test.js from [b56d183212] to [e8bb9fea35].

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
...
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
...
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
...
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
...
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307

    expect(result.stackElement()).toBe(8);
});

test('Int match', async () => {
    const wat = await compiler.toWat('main', `
        defmulti: double
        : Int( value 0 )
          drop 2
        : Int
          2 *

        def: main
        : 0 double
    `);
................................................................................

    expect(result.stackElement()).toBe(2);
});

test('Int match (reverse)', async () => {
    const wat = await compiler.toWat('main', `
        defmulti: double
        : Int( value 0 )
          drop 2
        : Int
          2 *

        def: main
        : 6 double
    `);
................................................................................

    expect(result.stackElement()).toBe(12);
});

test('Correct Int boxing behaviour', async () => {
    const wat = await compiler.toWat('main', `
        defmulti: add
        : Int( value 0 )
          swap 
          drop 2
          swap
          +
        : Int
          +

................................................................................
});

test('Correct Int boxing behaviour when mismatch between word input size and stack size', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Nil

        defmulti: inc-zero
        : Int( value 0 )
          swap 
          drop 1
          swap
        : Int

        def: main
        : 0 Nil> inc-zero
................................................................................
test('Cyclic case', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : 10 count-down

        defmulti: count-down
        type: Int -- Int
        : Int( value 0 )
          drop 0
        : Int
          dec-count-down

        def: dec-count-down
        : 1 - count-down
    `);

    const result = await compiler.run(wat, 'main');

    expect(result.stackElement()).toBe(0);
});







|







 







|







 







|







 







|







 







|












176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
...
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
...
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
...
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
...
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307

    expect(result.stackElement()).toBe(8);
});

test('Int match', async () => {
    const wat = await compiler.toWat('main', `
        defmulti: double
        : 0
          drop 2
        : Int
          2 *

        def: main
        : 0 double
    `);
................................................................................

    expect(result.stackElement()).toBe(2);
});

test('Int match (reverse)', async () => {
    const wat = await compiler.toWat('main', `
        defmulti: double
        : 0
          drop 2
        : Int
          2 *

        def: main
        : 6 double
    `);
................................................................................

    expect(result.stackElement()).toBe(12);
});

test('Correct Int boxing behaviour', async () => {
    const wat = await compiler.toWat('main', `
        defmulti: add
        : 0
          swap 
          drop 2
          swap
          +
        : Int
          +

................................................................................
});

test('Correct Int boxing behaviour when mismatch between word input size and stack size', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Nil

        defmulti: inc-zero
        : 0
          swap 
          drop 1
          swap
        : Int

        def: main
        : 0 Nil> inc-zero
................................................................................
test('Cyclic case', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : 10 count-down

        defmulti: count-down
        type: Int -- Int
        : 0
          drop 0
        : Int
          dec-count-down

        def: dec-count-down
        : 1 - count-down
    `);

    const result = await compiler.run(wat, 'main');

    expect(result.stackElement()).toBe(0);
});