Stabel

Check-in [e155197c9a]
Login
Overview
Comment:Add support for modules. Fixes [57c2233d50] and [abaac5803b]
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: e155197c9a523742644762150f827624b82337a96c35f0d065695f13794675b4
User & Date: robin.hansen on 2021-06-02 10:02:36
Other Links: manifest | tags
Context
2021-06-03
08:46
Update dependencies check-in: 001e644fe1 user: robin.hansen tags: trunk
2021-06-02
10:02
Add support for modules. Fixes [57c2233d50] and [abaac5803b] check-in: e155197c9a user: robin.hansen tags: trunk
09:59
Format errors from CLI. Closed-Leaf check-in: 742e0c8355 user: robin.hansen tags: module-definition
2021-04-17
11:05
First implementation of the standard library. check-in: 7e9c8cf531 user: robin.hansen tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Modified package-lock.json from [8a88db7fc1] to [72c5ce867e].

5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
      "integrity": "sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA==",
      "dev": true,
      "requires": {
        "xml-name-validator": "^3.0.0"
      }
    },
    "wabt": {
      "version": "1.0.20",
      "resolved": "https://registry.npmjs.org/wabt/-/wabt-1.0.20.tgz",
      "integrity": "sha512-chkTTrB1XolSLs6lBk7/U5oXaxUMECeJOiMuiTHYgC8BS0EToJGFXuL5Dgggv2S+SS78GQ8YPovRrmUwT7pOlQ==",
      "dev": true
    },
    "walker": {
      "version": "1.0.7",
      "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz",
      "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=",
      "dev": true,







|
|
|







5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
      "integrity": "sha512-4tzD0mF8iSiMiNs30BiLO3EpfGLZUT2MSX/G+o7ZywDzliWQ3OPtTZ0PTC3B3ca1UAf4cJMHB+2Bf56EriJuRA==",
      "dev": true,
      "requires": {
        "xml-name-validator": "^3.0.0"
      }
    },
    "wabt": {
      "version": "1.0.23",
      "resolved": "https://registry.npmjs.org/wabt/-/wabt-1.0.23.tgz",
      "integrity": "sha512-gN1CPmpqDenmNhUmybOCa2ZsE87oTnSZ/eLfNuNsS6753O3EGdB9pNb9ETH5GHHJZeAlxVgzH3MztMCEBiLj/w==",
      "dev": true
    },
    "walker": {
      "version": "1.0.7",
      "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz",
      "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=",
      "dev": true,

Modified package.json from [895cd12b4c] to [3fe7f8c176].

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  "dependencies": {},
  "devDependencies": {
    "elm": "^0.19.1-5",
    "elm-format": "^0.8.5",
    "elm-test": "^0.19.1-revision6",
    "jest": "^26.6.3",
    "strip-indent": "^3.0.0",
    "wabt": "^1.0.20"
  },
  "scripts": {
    "test": "npm run test:elm && npm run test:wasm",
    "test:elm": "elm-test",
    "test:elm:watch": "elm-test --watch",
    "test:wasm": "elm make src/Main.elm --output wasm_tests/compiler.js && sed -i '' \"s/console.warn\\(.*\\);/\\/*&*\\//g\" wasm_tests/compiler.js && jest",
    "build": "elm make src/CLI.elm --output bin/compiler.js && sed -i '' \"s/console.warn\\(.*\\);/\\/*&*\\//g\" bin/compiler.js"
  },
  "bin": {
    "play": "bin/cli.js"
  }
}







|





|






7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  "dependencies": {},
  "devDependencies": {
    "elm": "^0.19.1-5",
    "elm-format": "^0.8.5",
    "elm-test": "^0.19.1-revision6",
    "jest": "^26.6.3",
    "strip-indent": "^3.0.0",
    "wabt": "^1.0.23"
  },
  "scripts": {
    "test": "npm run test:elm && npm run test:wasm",
    "test:elm": "elm-test",
    "test:elm:watch": "elm-test --watch",
    "test:wasm": "elm make src/TestCompiler.elm --output wasm_tests/compiler.js && sed -i '' \"s/console.warn\\(.*\\);/\\/*&*\\//g\" wasm_tests/compiler.js && jest",
    "build": "elm make src/CLI.elm --output bin/compiler.js && sed -i '' \"s/console.warn\\(.*\\);/\\/*&*\\//g\" bin/compiler.js"
  },
  "bin": {
    "play": "bin/cli.js"
  }
}

Modified src/CLI.elm from [2a2a2f3219] to [c955eddac9].

90
91
92
93
94
95
96

97

98
99
100
101
102
103
104
                                Err error ->
                                    ( model
                                    , outgoingPort <| encodeCompilationFailure error
                                    )

                        PackageLoader.Failed error ->
                            ( model

                            , outgoingPort <| encodeCompilationFailure <| Debug.toString error

                            )

                        _ ->
                            ( updatedModel
                            , sendSideEffectFromModel updatedModel
                            )








>
|
>







90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
                                Err error ->
                                    ( model
                                    , outgoingPort <| encodeCompilationFailure error
                                    )

                        PackageLoader.Failed error ->
                            ( model
                            , outgoingPort <|
                                encodeCompilationFailure <|
                                    PackageLoader.problemToString error
                            )

                        _ ->
                            ( updatedModel
                            , sendSideEffectFromModel updatedModel
                            )

Modified src/Play/Data/Metadata.elm from [66ac0fbdbc] to [4a5e9363a6].

1
2

3
4
5
6
7
8
9
10
11
12

13
14
15
16
17
18
19
20
21

22
23
24
25
26
27
28
..
46
47
48
49
50
51
52





module Play.Data.Metadata exposing (..)


import Play.Data.SourceLocation exposing (SourceLocationRange)
import Play.Data.Type exposing (Type)
import Play.Data.TypeSignature exposing (TypeSignature(..))


type alias Metadata =
    { isEntryPoint : Bool
    , type_ : TypeSignature
    , isQuoted : Bool
    , sourceLocationRange : Maybe SourceLocationRange

    }


default : Metadata
default =
    { isEntryPoint = False
    , type_ = NotProvided
    , isQuoted = False
    , sourceLocationRange = Nothing

    }


asEntryPoint : Metadata -> Metadata
asEntryPoint meta =
    { meta | isEntryPoint = True }

................................................................................
withSourceLocationRange range meta =
    { meta | sourceLocationRange = Just range }


clearSourceLocationRange : Metadata -> Metadata
clearSourceLocationRange meta =
    { meta | sourceLocationRange = Nothing }







>










>









>







 







>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
..
49
50
51
52
53
54
55
56
57
58
59
60
module Play.Data.Metadata exposing (..)

import Dict exposing (Dict)
import Play.Data.SourceLocation exposing (SourceLocationRange)
import Play.Data.Type exposing (Type)
import Play.Data.TypeSignature exposing (TypeSignature(..))


type alias Metadata =
    { isEntryPoint : Bool
    , type_ : TypeSignature
    , isQuoted : Bool
    , sourceLocationRange : Maybe SourceLocationRange
    , isExposed : Bool
    }


default : Metadata
default =
    { isEntryPoint = False
    , type_ = NotProvided
    , isQuoted = False
    , sourceLocationRange = Nothing
    , isExposed = True
    }


asEntryPoint : Metadata -> Metadata
asEntryPoint meta =
    { meta | isEntryPoint = True }

................................................................................
withSourceLocationRange range meta =
    { meta | sourceLocationRange = Just range }


clearSourceLocationRange : Metadata -> Metadata
clearSourceLocationRange meta =
    { meta | sourceLocationRange = Nothing }


isExposed : Bool -> Metadata -> Metadata
isExposed val meta =
    { meta | isExposed = val }

Modified src/Play/PackageLoader.elm from [41ef8f9010] to [2e56b7cc2e].

1
2
3
4
5
6
7

8
9
10
11
12
13
14
15
16
17
18
19
20

21

22
23
24
25
26
27
28
29
30


31
32





























33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68









69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
...
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
...
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
...
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
...
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442






443
444
445
446
447
448
449
450
451
452
453
454
455


456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516

































517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534


535
536

537
538



539
540
541
542
543
544
545
546
547
548
549


550

551




















module Play.PackageLoader exposing
    ( Model(..)
    , Msg(..)
    , Problem(..)
    , SideEffect(..)
    , getSideEffect
    , init

    , update
    )

import Dict exposing (Dict)
import Json.Decode as Json
import List.Extra as List
import Play.Data.Metadata as Metadata
import Play.Data.ModuleName as ModuleName exposing (ModuleName)
import Play.Data.PackageMetadata as PackageMetadata exposing (PackageMetadata)
import Play.Data.PackageName as PackageName exposing (PackageName)
import Play.Data.PackagePath as PackagePath exposing (PackagePath)
import Play.Data.SemanticVersion as SemanticVersion exposing (SemanticVersion)
import Play.Parser as Parser

import Play.Qualifier as Qualifier

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


type Problem
    = InvalidPackageMetadata String String
    | UnknownMessageForState String
    | NoExposedModulesInRootProject
    | ModuleNotFound String


    | InternalError String































type alias InitOptions =
    { projectDirPath : String
    , stdLibPath : String
    , possibleEntryPoint : Maybe String
    }


type Model
    = Initializing InitOptions SideEffect
    | LoadingMetadata State (List PackagePath) SideEffect
    | ResolvingModulePaths State (List PackageInfo) SideEffect
    | Compiling State (List ( PackageInfo, ModuleName )) SideEffect
    | Done Qualifier.ExposedAST
    | Failed Problem


type alias State =
    { possibleEntryPoint : Maybe String
    , rootPackage : PackageInfo
    , dependencies : Dict String SemanticVersion
    , dependentPackages : Dict String PackageInfo
    , filePathToModule : Dict String ( PackageName, ModuleName )
    , moduleNameToPackageName : Dict String String
    , absoluteModuleNameToDetails : Dict String ( PackageInfo, ModuleName )
    , inProgressAst : Maybe Qualifier.AST
    , parsedModules : Set String
    }


type alias PackageInfo =
    { path : String
    , metadata : PackageMetadata
    , modules : List ModuleName
    }











emptyState : InitOptions -> PackageInfo -> State
emptyState initOptions rootPackage =
    { possibleEntryPoint = initOptions.possibleEntryPoint
    , rootPackage = rootPackage
    , dependencies = rootPackage.metadata.dependencies
    , dependentPackages = Dict.empty
    , filePathToModule = Dict.empty
    , moduleNameToPackageName = Dict.empty
    , absoluteModuleNameToDetails = Dict.empty
    , inProgressAst = Nothing
    , parsedModules = Set.empty
    }


type Msg
    = FileContents String String String
    | ResolvedDirectories String (List PackagePath)
    | ResolvedPackageModules String (List String)
................................................................................

        LoadingMetadata _ _ sf ->
            Just sf

        ResolvingModulePaths _ _ sf ->
            Just sf

        Compiling _ _ sf ->
            Just sf


init : InitOptions -> Model
init initOptions =
    Initializing initOptions <|
        ReadFile initOptions.projectDirPath "play.json"
................................................................................

        LoadingMetadata state remainingPaths _ ->
            loadingMetadataUpdate msg state remainingPaths

        ResolvingModulePaths state remainingPackages _ ->
            resolvingModulePathsUpdate msg state remainingPackages

        Compiling state remainingModules _ ->
            compilingUpdate msg state remainingModules

        Done _ ->
            model

        Failed _ ->
            model

................................................................................

                    absoluteNameToDetails =
                        allPackages
                            |> List.concatMap (\pInfo -> List.map (\m -> ( pInfo, m )) pInfo.modules)
                            |> List.map (\( pInfo, mName ) -> ( absoluteModuleName pInfo.metadata.name mName, ( pInfo, mName ) ))
                            |> Dict.fromList
                in
                Compiling
                    { state
                        | filePathToModule = pathsToModuleNames
                        , moduleNameToPackageName = moduleNameToPackageName
                        , absoluteModuleNameToDetails = absoluteNameToDetails
                    }
                    (List.map (\m -> ( state.rootPackage, m )) remModules)
                    (ReadFile path fileName)
................................................................................
                )
                package.modules
                |> Dict.fromList
    in
    Dict.union acc absolutePathsForModule


compilingUpdate : Msg -> State -> List ( PackageInfo, ModuleName ) -> Model
compilingUpdate msg state remainingModules =
    case msg of
        FileContents path fileName content ->
            let
                fullPath =
                    path ++ "/" ++ fileName

                possibleModuleInfo =
                    Dict.get fullPath state.filePathToModule
            in
            case ( possibleModuleInfo, Parser.run content ) of
                ( _, Err parserError ) ->
                    Failed <| InternalError <| "Parser error: " ++ Debug.toString parserError

                ( Just ( packageName, moduleName ), Ok parserAst ) ->
                    let
                        qualifierResult =






                            Qualifier.run
                                { packageName = PackageName.toString packageName
                                , modulePath = ModuleName.toString moduleName
                                , ast = parserAst
                                , externalModules = state.moduleNameToPackageName
                                }
                    in
                    case qualifierResult of
                        Err qualifierError ->
                            Failed <| InternalError <| "Qualifier error: " ++ Debug.toString qualifierError

                        Ok qualifiedAST ->
                            let


                                fullModuleName =
                                    absoluteModuleName packageName moduleName

                                mergedQualifiedAst =
                                    state.inProgressAst
                                        |> Maybe.map
                                            (\ipa ->
                                                { additionalModulesRequired =
                                                    Set.union
                                                        ipa.additionalModulesRequired
                                                        qualifiedAST.additionalModulesRequired
                                                , checkForExistingTypes =
                                                    Set.union
                                                        ipa.checkForExistingTypes
                                                        qualifiedAST.checkForExistingTypes
                                                , checkForExistingWords =
                                                    Set.union
                                                        ipa.checkForExistingWords
                                                        qualifiedAST.checkForExistingWords
                                                , types = Dict.union ipa.types qualifiedAST.types
                                                , words = Dict.union ipa.words qualifiedAST.words
                                                }
                                            )
                                        |> Maybe.withDefault qualifiedAST


                                updatedParsedModules =
                                    Set.insert fullModuleName state.parsedModules

                                modulesQueuedForOrAlreadyParsed =
                                    remainingModules
                                        |> List.map (\( pInfo, mName ) -> absoluteModuleName pInfo.metadata.name mName)
                                        |> Set.fromList
                                        |> Set.union updatedParsedModules

                                missingModulesInParseQueue =
                                    Set.diff mergedQualifiedAst.additionalModulesRequired modulesQueuedForOrAlreadyParsed
                                        |> Set.toList
                                        |> List.filterMap (\absName -> Dict.get absName state.absoluteModuleNameToDetails)

                                updatedRemainingModules =
                                    missingModulesInParseQueue ++ remainingModules
                            in
                            nextCompileStep updatedParsedModules mergedQualifiedAst updatedRemainingModules state

                ( Nothing, _ ) ->
                    Failed <| InternalError <| "Don't know why we read file: " ++ fullPath

        _ ->
            Failed <| InternalError <| "Unknown message for compile stage: " ++ Debug.toString msg


absoluteModuleName : PackageName -> ModuleName -> String
absoluteModuleName packageName moduleName =
    "/" ++ PackageName.toString packageName ++ "/" ++ ModuleName.toString moduleName


nextCompileStep : Set String -> Qualifier.AST -> List ( PackageInfo, ModuleName ) -> State -> Model
nextCompileStep parsedModules inProgressAst remainingModules state =
    case remainingModules of
        [] ->
            let

































                wordsWithEntryPoint =
                    state.possibleEntryPoint
                        |> Maybe.map (setEntryPoint inProgressAst.words)
                        |> Maybe.withDefault inProgressAst.words

                setEntryPoint words entryPointName =
                    Dict.update
                        entryPointName
                        (\maybeWord ->
                            case maybeWord of
                                Nothing ->
                                    Nothing

                                Just word ->
                                    Just { word | metadata = Metadata.asEntryPoint word.metadata }
                        )
                        words
            in


            Done
                { types = inProgressAst.types

                , words = wordsWithEntryPoint
                }




        ( packageInfo, moduleName ) :: otherModules ->
            let
                ( path, fileName ) =
                    readModuleFromDisk packageInfo.path moduleName
            in
            Compiling
                { state
                    | parsedModules = parsedModules
                    , inProgressAst = Just inProgressAst
                }


                otherModules

                (ReadFile path fileName)



























>













>

>









>
>


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












|
|











|
|









>
>
>
>
>
>
>
>
>










|
|







 







|







 







|
|







 







|







 







|
|











|



|
>
>
>
>
>
>
|

<



<
<
<
<

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

|
|
|
|
|

|
|
|
|

|
|
|
|













|
|



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


|
|




<
<
<
<
<
<
|
<


>
>
|
<
>
|
|
>
>
>






|
<
<
<
|
>
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
...
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
...
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
...
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
...
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493

494
495
496




497

498
499
500
501
502


503
504
505
506













507


508
509


510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584






585

586
587
588
589
590

591
592
593
594
595
596
597
598
599
600
601
602
603



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
module Play.PackageLoader exposing
    ( Model(..)
    , Msg(..)
    , Problem(..)
    , SideEffect(..)
    , getSideEffect
    , init
    , problemToString
    , update
    )

import Dict exposing (Dict)
import Json.Decode as Json
import List.Extra as List
import Play.Data.Metadata as Metadata
import Play.Data.ModuleName as ModuleName exposing (ModuleName)
import Play.Data.PackageMetadata as PackageMetadata exposing (PackageMetadata)
import Play.Data.PackageName as PackageName exposing (PackageName)
import Play.Data.PackagePath as PackagePath exposing (PackagePath)
import Play.Data.SemanticVersion as SemanticVersion exposing (SemanticVersion)
import Play.Parser as Parser
import Play.Parser.Problem as ParserProblem
import Play.Qualifier as Qualifier
import Play.Qualifier.Problem as QualifierProblem
import Result.Extra as Result
import Set exposing (Set)


type Problem
    = InvalidPackageMetadata String String
    | UnknownMessageForState String
    | NoExposedModulesInRootProject
    | ModuleNotFound String
    | ParserError String (List ParserProblem.Problem)
    | QualifierError String (List QualifierProblem.Problem)
    | InternalError String


problemToString : Problem -> String
problemToString problem =
    case problem of
        InvalidPackageMetadata path err ->
            "Something is wrong with file located at '" ++ path ++ "':\n\n" ++ err

        UnknownMessageForState msg ->
            "Unknown message for state: " ++ msg

        NoExposedModulesInRootProject ->
            "No exposed modules in root project"

        ModuleNotFound mod ->
            "Failed to locate module '" ++ mod ++ "' on disk"

        ParserError source errs ->
            errs
                |> List.map (ParserProblem.toString source)
                |> String.join "\n\n"

        QualifierError source errs ->
            errs
                |> List.map (QualifierProblem.toString source)
                |> String.join "\n\n"

        InternalError msg ->
            "Internal error: " ++ msg


type alias InitOptions =
    { projectDirPath : String
    , stdLibPath : String
    , possibleEntryPoint : Maybe String
    }


type Model
    = Initializing InitOptions SideEffect
    | LoadingMetadata State (List PackagePath) SideEffect
    | ResolvingModulePaths State (List PackageInfo) SideEffect
    | Parsing State (List ( PackageInfo, ModuleName )) SideEffect
    | Done Qualifier.AST
    | Failed Problem


type alias State =
    { possibleEntryPoint : Maybe String
    , rootPackage : PackageInfo
    , dependencies : Dict String SemanticVersion
    , dependentPackages : Dict String PackageInfo
    , filePathToModule : Dict String ( PackageName, ModuleName )
    , moduleNameToPackageName : Dict String String
    , absoluteModuleNameToDetails : Dict String ( PackageInfo, ModuleName )
    , parsedModuleNames : Set String
    , parsedModules : List ParsedModuleInfo
    }


type alias PackageInfo =
    { path : String
    , metadata : PackageMetadata
    , modules : List ModuleName
    }


type alias ParsedModuleInfo =
    { packageName : PackageName
    , modulePath : ModuleName
    , ast : Parser.AST
    , requiredModules : Set String
    , source : String
    }


emptyState : InitOptions -> PackageInfo -> State
emptyState initOptions rootPackage =
    { possibleEntryPoint = initOptions.possibleEntryPoint
    , rootPackage = rootPackage
    , dependencies = rootPackage.metadata.dependencies
    , dependentPackages = Dict.empty
    , filePathToModule = Dict.empty
    , moduleNameToPackageName = Dict.empty
    , absoluteModuleNameToDetails = Dict.empty
    , parsedModuleNames = Set.empty
    , parsedModules = []
    }


type Msg
    = FileContents String String String
    | ResolvedDirectories String (List PackagePath)
    | ResolvedPackageModules String (List String)
................................................................................

        LoadingMetadata _ _ sf ->
            Just sf

        ResolvingModulePaths _ _ sf ->
            Just sf

        Parsing _ _ sf ->
            Just sf


init : InitOptions -> Model
init initOptions =
    Initializing initOptions <|
        ReadFile initOptions.projectDirPath "play.json"
................................................................................

        LoadingMetadata state remainingPaths _ ->
            loadingMetadataUpdate msg state remainingPaths

        ResolvingModulePaths state remainingPackages _ ->
            resolvingModulePathsUpdate msg state remainingPackages

        Parsing state remainingModules _ ->
            parsingUpdate msg state remainingModules

        Done _ ->
            model

        Failed _ ->
            model

................................................................................

                    absoluteNameToDetails =
                        allPackages
                            |> List.concatMap (\pInfo -> List.map (\m -> ( pInfo, m )) pInfo.modules)
                            |> List.map (\( pInfo, mName ) -> ( absoluteModuleName pInfo.metadata.name mName, ( pInfo, mName ) ))
                            |> Dict.fromList
                in
                Parsing
                    { state
                        | filePathToModule = pathsToModuleNames
                        , moduleNameToPackageName = moduleNameToPackageName
                        , absoluteModuleNameToDetails = absoluteNameToDetails
                    }
                    (List.map (\m -> ( state.rootPackage, m )) remModules)
                    (ReadFile path fileName)
................................................................................
                )
                package.modules
                |> Dict.fromList
    in
    Dict.union acc absolutePathsForModule


parsingUpdate : Msg -> State -> List ( PackageInfo, ModuleName ) -> Model
parsingUpdate msg state remainingModules =
    case msg of
        FileContents path fileName content ->
            let
                fullPath =
                    path ++ "/" ++ fileName

                possibleModuleInfo =
                    Dict.get fullPath state.filePathToModule
            in
            case ( possibleModuleInfo, Parser.run content ) of
                ( _, Err parserError ) ->
                    Failed <| ParserError content parserError

                ( Just ( packageName, moduleName ), Ok parserAst ) ->
                    let
                        fullModuleName =
                            absoluteModuleName packageName moduleName

                        updatedParsedModules =
                            Set.insert fullModuleName state.parsedModuleNames

                        requiredModules =
                            Qualifier.requiredModules
                                { packageName = PackageName.toString packageName

                                , ast = parserAst
                                , externalModules = state.moduleNameToPackageName
                                }






                        updatedState =
                            { state
                                | parsedModuleNames = updatedParsedModules
                                , parsedModules =
                                    { packageName = packageName


                                    , modulePath = moduleName
                                    , ast = parserAst
                                    , requiredModules = requiredModules
                                    , source = content













                                    }


                                        :: state.parsedModules
                            }



                        modulesQueuedForOrAlreadyParsed =
                            remainingModules
                                |> List.map (\( pInfo, mName ) -> absoluteModuleName pInfo.metadata.name mName)
                                |> Set.fromList
                                |> Set.union updatedParsedModules

                        missingModulesInParseQueue =
                            Set.diff requiredModules modulesQueuedForOrAlreadyParsed
                                |> Set.toList
                                |> List.filterMap (\absName -> Dict.get absName state.absoluteModuleNameToDetails)

                        updatedRemainingModules =
                            remainingModules ++ missingModulesInParseQueue
                    in
                    nextCompileStep updatedRemainingModules updatedState

                ( Nothing, _ ) ->
                    Failed <| InternalError <| "Don't know why we read file: " ++ fullPath

        _ ->
            Failed <| InternalError <| "Unknown message for compile stage: " ++ Debug.toString msg


absoluteModuleName : PackageName -> ModuleName -> String
absoluteModuleName packageName moduleName =
    "/" ++ PackageName.toString packageName ++ "/" ++ ModuleName.toString moduleName


nextCompileStep : List ( PackageInfo, ModuleName ) -> State -> Model
nextCompileStep remainingModules state =
    case remainingModules of
        [] ->
            let
                sortedParsedModules =
                    List.sortWith sortByRequiredModules state.parsedModules

                ( qualifiedAst, errs ) =
                    sortedParsedModules
                        |> List.foldl qualifyAst ( { types = Dict.empty, words = Dict.empty }, [] )

                qualifyAst parsedModInfo ( qast, es ) =
                    let
                        qualifierResult =
                            Qualifier.run
                                { packageName = PackageName.toString parsedModInfo.packageName
                                , modulePath = ModuleName.toString parsedModInfo.modulePath
                                , ast = parsedModInfo.ast
                                , externalModules = state.moduleNameToPackageName
                                , inProgressAST = qast
                                }
                    in
                    case qualifierResult of
                        Err qualifierError ->
                            ( qast
                            , QualifierError parsedModInfo.source qualifierError :: es
                            )

                        Ok qualifiedAST ->
                            let
                                mergedQualifiedAst =
                                    { types = Dict.union qast.types qualifiedAST.types
                                    , words = Dict.union qast.words qualifiedAST.words
                                    }
                            in
                            ( mergedQualifiedAst, es )

                wordsWithEntryPoint =
                    state.possibleEntryPoint
                        |> Maybe.map (setEntryPoint qualifiedAst.words)
                        |> Maybe.withDefault qualifiedAst.words

                setEntryPoint words entryPointName =
                    Dict.update
                        entryPointName






                        (Maybe.map (\w -> { w | metadata = Metadata.asEntryPoint w.metadata }))

                        words
            in
            case errs of
                [] ->
                    Done

                        { types = qualifiedAst.types
                        , words = wordsWithEntryPoint
                        }

                err :: _ ->
                    Failed <| err

        ( packageInfo, moduleName ) :: otherModules ->
            let
                ( path, fileName ) =
                    readModuleFromDisk packageInfo.path moduleName
            in
            Parsing state otherModules (ReadFile path fileName)





sortByRequiredModules : ParsedModuleInfo -> ParsedModuleInfo -> Order
sortByRequiredModules a b =
    let
        aQualifiedName =
            absoluteModuleName a.packageName a.modulePath

        bQualifiedName =
            absoluteModuleName b.packageName b.modulePath

        aRequiredByB =
            Set.member aQualifiedName b.requiredModules

        bRequiredByA =
            Set.member bQualifiedName a.requiredModules
    in
    case ( aRequiredByB, bRequiredByA ) of
        ( True, False ) ->
            LT

        ( False, True ) ->
            GT

        otherwise ->
            EQ

Modified src/Play/Parser.elm from [f9f02c0303] to [fcb864ece6].

1
2
3



4
5
6

7
8

9
10

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

29
30
31
32
33












34
35
36
37
38
39
40
41



42
43
44


































45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
..
74
75
76
77
78
79
80













81
82
83
84
85
86
87
..
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
...
160
161
162
163
164
165
166

















167
168
169
170
171
172
173
...
177
178
179
180
181
182
183










184
185
186
187
188
189
190
...
232
233
234
235
236
237
238





















239
240
241
242
243
244
245
...
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305

306
307
308
309
310
311
312
313
314
315






316
317

318



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339







340
341
342
343
344
345
346
347
348
349
350























351





















352
353
354
355
356
357
358
359
360
361
362
363
...
379
380
381
382
383
384
385



386

387
388
389
390
391
392




393



394
395







































396
397
398
399
400
401
402
...
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
...
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503





504
505
506
507
508
509
510
511
512





513
514
515
516
517
518
519
520





521
522
523
524
525
526
527
...
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571





572




573
574
575
576
577
578
579
...
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
...
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
...
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
...
682
683
684
685
686
687
688


689
690
691
692
693
694
695
696
...
714
715
716
717
718
719
720
721


722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743


744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
module Play.Parser exposing
    ( AST
    , AstNode(..)



    , TypeDefinition(..)
    , TypeMatch(..)
    , TypeMatchValue(..)

    , WordDefinition
    , WordImplementation(..)

    , run
    , typeDefinitionName

    )

import Dict exposing (Dict)
import Dict.Extra as Dict
import Parser.Advanced as Parser exposing ((|.), (|=), Token(..))
import Play.Data.Metadata as Metadata exposing (Metadata)
import Play.Data.SourceLocation exposing (SourceLocation, SourceLocationRange)
import Play.Data.Type as Type exposing (Type, WordType)
import Play.Data.TypeSignature as TypeSignature
import Play.Parser.Problem exposing (..)
import Set exposing (Set)


type alias Parser a =
    Parser.Parser () Problem a


type alias AST =

    { types : Dict String TypeDefinition
    , words : Dict String WordDefinition
    }














type TypeDefinition
    = CustomTypeDef SourceLocationRange String (List String) (List ( String, Type ))
    | UnionTypeDef SourceLocationRange String (List String) (List Type)


type alias WordDefinition =
    { name : String
    , metadata : Metadata



    , implementation : WordImplementation
    }




































type WordImplementation
    = 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
    = Integer SourceLocationRange Int
    | Word SourceLocationRange String
    | PackageWord SourceLocationRange (List String) String
................................................................................
    Parser.run parser sourceCode
        |> Result.mapError (List.map .problem)



-- ATOMS















validSymbolChar : Char -> Bool
validSymbolChar c =
    not <| Set.member c invalidSymbolChars


invalidSymbolChars : Set Char
................................................................................
        , '{'
        , '}'
        , '['
        , ']'
        , '('
        , ')'
        , '.'
        , ','
        , '#'
        , '/'
        ]


whitespaceChars : Set Char
whitespaceChars =
................................................................................
                |. Parser.symbol (Token ":" NotMetadata)
                |> Parser.andThen (\_ -> Parser.problem FoundMetadata)
            , Parser.succeed identity
            ]
        |. noiseParser
        |> Parser.backtrackable



















symbolImplParser : Parser String
symbolImplParser =
    Parser.variable
        { start = \c -> not (Char.isDigit c || Set.member c invalidSymbolChars)
        , inner = validSymbolChar
        , reserved = Set.empty
................................................................................
            [ Parser.succeed identity
                |. Parser.symbol (Token ":" NotMetadata)
                |> Parser.andThen (\_ -> Parser.problem FoundMetadata)
            , Parser.succeed identity
            ]
        |> Parser.backtrackable












symbolImplParser2 : Parser (SourceLocationRange -> AstNode)
symbolImplParser2 =
    let
        externalBuilder firstSymbol (( partialPath, reference ) as modulePathResult) =
            let
                path =
................................................................................
                [ Parser.loop [] modulePathParser
                , Parser.succeed ( [], "" )
                ]
        ]
        |. noiseParser
        |> Parser.andThen identity























modulePathParser : List String -> Parser (Parser.Step (List String) ( List String, String ))
modulePathParser symbols =
    Parser.oneOf
        [ Parser.succeed (\name -> Parser.Loop (name :: symbols))
            |. Parser.symbol (Token "/" NotMetadata)
            |= symbolImplParser
................................................................................
        , inner = validSymbolChar
        , reserved = Set.empty
        , expecting = NotType
        }
        |. noiseParser


genericOrRangeParser : Parser Type
genericOrRangeParser =
    let
        helper value =
            Parser.oneOf
                [ Parser.succeed (Type.StackRange value)
                    |. Parser.symbol (Token "..." NoProblem)
                    |. noiseParser
                , Parser.succeed (Type.Generic value)

                ]
    in
    Parser.andThen helper genericParser


typeParser : Parser Type
typeParser =
    Parser.oneOf
        [ Parser.succeed Type.Int
            |. Parser.keyword (Token "Int" NoProblem)






            |. noiseParser
        , Parser.succeed Type.Custom

            |= typeNameParser



        ]


typeRefParser : Parser Type
typeRefParser =
    let
        helper name binds =
            case binds of
                [] ->
                    Type.Custom name

                _ ->
                    Type.CustomGeneric name binds
    in
    Parser.oneOf
        [ Parser.succeed Type.Int
            |. Parser.keyword (Token "Int" NoProblem)
            |. noiseParser
        , Parser.succeed helper
            |= typeNameParser
            |= Parser.loop [] typeOrGenericParser







        , Parser.succeed Type.Generic
            |= genericParser
        , Parser.succeed identity
            |. Parser.symbol (Token "(" ExpectedLeftParen)
            |. noiseParser
            |= Parser.lazy (\_ -> typeRefParser)
            |. Parser.symbol (Token ")" ExpectedRightParen)
            |. noiseParser
        ]

























typeOrGenericParser : List Type -> Parser (Parser.Step (List Type) (List Type))





















typeOrGenericParser types =
    Parser.oneOf
        [ Parser.succeed (\name -> Parser.Loop (Type.Custom name :: types))
            |= typeNameParser
        , Parser.succeed (\name -> Parser.Loop (Type.Generic name :: types))
            |= genericParser
        , Parser.succeed (Parser.Done (List.reverse types))
        ]


noiseParser : Parser ()
noiseParser =
................................................................................

-- Grammar


parser : Parser AST
parser =
    let



        emptyAst =

            { types = Dict.empty
            , words = Dict.empty
            }
    in
    Parser.succeed identity
        |. noiseParser




        |= Parser.loop emptyAst definitionParser



        |. Parser.end ExpectedEnd









































definitionParser : AST -> Parser (Parser.Step AST AST)
definitionParser ast =
    let
        insertWord wordDef =
            case maybeInsertWordProblem wordDef of
                Just problem ->
................................................................................
                        |> Parser.succeed

        maybeInsertWordProblem wordDef =
            Dict.get wordDef.name ast.words
                |> Maybe.map
                    (\prevDef ->
                        WordAlreadyDefined wordDef.name
                            prevDef.metadata.sourceLocationRange
                            wordDef.metadata.sourceLocationRange
                    )

        insertType typeDef =
            let
                typeName =
                    typeDefinitionName typeDef
            in
................................................................................
    case typeDef of
        UnionTypeDef _ _ _ _ ->
            []

        CustomTypeDef _ typeName binds typeMembers ->
            let
                typeOfType =
                    case binds of
                        [] ->
                            Type.Custom typeName

                        _ ->
                            Type.CustomGeneric typeName (List.map Type.Generic binds)

                ctorDef =
                    { name =
                        if List.isEmpty typeMembers then
                            typeName

                        else
                            ">" ++ typeName
                    , metadata =
                        Metadata.default
                            |> Metadata.withVerifiedType (List.map Tuple.second typeMembers) [ typeOfType ]





                    , implementation =
                        SoloImpl [ ConstructType typeName ]
                    }

                setterGetterPair ( memberName, memberType ) =
                    [ { name = ">" ++ memberName
                      , metadata =
                            Metadata.default
                                |> Metadata.withVerifiedType [ typeOfType, memberType ] [ typeOfType ]





                      , implementation =
                            SoloImpl
                                [ SetMember typeName memberName ]
                      }
                    , { name = memberName ++ ">"
                      , metadata =
                            Metadata.default
                                |> Metadata.withVerifiedType [ typeOfType ] [ memberType ]





                      , implementation =
                            SoloImpl
                                [ GetMember typeName memberName ]
                      }
                    ]
            in
            typeMembers
................................................................................

wordDefinitionParser : SourceLocation -> Parser WordDefinition
wordDefinitionParser startLocation =
    let
        joinParseResults name def endLocation =
            { def
                | name = name
                , metadata =
                    Metadata.withSourceLocationRange
                        { start = startLocation
                        , end = endLocation
                        }
                        def.metadata
            }

        emptyDef =
            { name = ""
            , metadata = Metadata.default



            , implementation = SoloImpl []
            }
    in
    Parser.succeed joinParseResults
        |= symbolParser
        |= Parser.loop emptyDef wordMetadataParser
        |= sourceLocationParser


wordMetadataParser : WordDefinition -> Parser (Parser.Step WordDefinition WordDefinition)
wordMetadataParser def =
    let
        metadata =
            def.metadata
    in
    Parser.oneOf
        [ Parser.succeed (\typeSign -> Parser.Loop { def | metadata = { metadata | type_ = TypeSignature.UserProvided typeSign } })
            |. Parser.keyword (Token "type:" NoProblem)
            |. noiseParser
            |= typeSignatureParser
        , Parser.succeed (Parser.Loop { def | metadata = { metadata | isEntryPoint = True } })
            |. Parser.keyword (Token "entry:" NoProblem)
            |. noiseParser





            |. Parser.keyword (Token "true" NoProblem)




            |. noiseParser
        , Parser.succeed (\impl -> Parser.Loop { def | implementation = SoloImpl impl })
            |. Parser.keyword (Token ":" NoProblem)
            |. noiseParser
            |= implementationParser
        , Parser.succeed UnknownMetadata
            |= definitionMetadataParser
................................................................................
multiWordDefinitionParser : SourceLocation -> Parser WordDefinition
multiWordDefinitionParser startLocation =
    let
        joinParseResults name def endLocation =
            reverseWhens <|
                { def
                    | name = name
                    , metadata =
                        Metadata.withSourceLocationRange
                            { start = startLocation
                            , end = endLocation
                            }
                            def.metadata
                }

        emptyDef =
            { name = ""
            , metadata = Metadata.default



            , implementation = SoloImpl []
            }

        reverseWhens def =
            case def.implementation of
                SoloImpl _ ->
                    def
................................................................................
        |= Parser.loop emptyDef multiWordMetadataParser
        |= sourceLocationParser


multiWordMetadataParser : WordDefinition -> Parser (Parser.Step WordDefinition WordDefinition)
multiWordMetadataParser def =
    let
        metadata =
            def.metadata

        addWhenImpl impl =
            case def.implementation of
                MultiImpl whens default ->
                    MultiImpl (impl :: whens) default

                SoloImpl default ->
                    MultiImpl [ impl ] default
................................................................................
                MultiImpl whens _ ->
                    MultiImpl whens impl

                SoloImpl _ ->
                    MultiImpl [] impl
    in
    Parser.oneOf
        [ Parser.succeed (\typeSign -> Parser.Loop { def | metadata = { metadata | type_ = TypeSignature.UserProvided typeSign } })
            |. Parser.keyword (Token "type:" NoProblem)
            |. noiseParser
            |= typeSignatureParser
        , Parser.succeed (\impl -> Parser.Loop { def | implementation = setDefaultImpl impl })
            |. Parser.keyword (Token "else:" NoProblem)
            |. noiseParser
            |= implementationParser
................................................................................
    Parser.oneOf
        [ Parser.succeed (\name -> Parser.Loop (name :: generics))
            |= genericParser
        , Parser.succeed (Parser.Done (List.reverse generics))
        ]




typeMemberParser : List ( String, Type ) -> Parser (Parser.Step (List ( String, Type )) (List ( String, Type )))
typeMemberParser types =
    Parser.oneOf
        [ Parser.succeed (\name type_ -> Parser.Loop (( name, type_ ) :: types))
            |. Parser.symbol (Token ":" NoProblem)
            |. noiseParser
            |= symbolParser
            |= typeRefParser
................................................................................
    Parser.succeed ctor
        |= typeNameParser
        |= Parser.loop [] typeGenericParser
        |= Parser.loop [] unionTypeMemberParser
        |= sourceLocationParser


unionTypeMemberParser : List Type -> Parser (Parser.Step (List Type) (List Type))


unionTypeMemberParser types =
    Parser.oneOf
        [ Parser.succeed (\type_ -> Parser.Loop (type_ :: types))
            |. Parser.symbol (Token ":" NoProblem)
            |. noiseParser
            |= typeRefParser
        , Parser.succeed UnknownMetadata
            |= definitionMetadataParser
            |> Parser.andThen Parser.problem
        , Parser.succeed (Parser.Done (List.reverse types))
        ]


typeSignatureParser : Parser WordType
typeSignatureParser =
    Parser.succeed (\input output -> { input = input, output = output })
        |= Parser.loop [] typeLoopParser
        |. Parser.symbol (Token "--" ExpectedTypeSeperator)
        |. noiseParser
        |= Parser.loop [] typeLoopParser




typeLoopParser : List Type -> Parser (Parser.Step (List Type) (List Type))
typeLoopParser reverseTypes =
    let
        step type_ =
            Parser.Loop (type_ :: reverseTypes)
    in
    Parser.oneOf
        [ Parser.succeed step
            |= typeParser
        , Parser.succeed step
            |= genericOrRangeParser
        , Parser.succeed step
            |= typeRefParser
        , Parser.succeed (\wordType -> step (Type.Quotation wordType))
            |. Parser.symbol (Token "[" ExpectedLeftBracket)
            |. noiseParser
            |= typeSignatureParser
            |. Parser.symbol (Token "]" ExpectedRightBracket)
            |. noiseParser
        , Parser.succeed (Parser.Done (List.reverse reverseTypes))
        ]


typeMatchParser : Parser TypeMatch
typeMatchParser =
    Parser.oneOf
        [ Parser.succeed (\startLoc type_ conds endLoc -> TypeMatch (SourceLocationRange startLoc endLoc) type_ conds)
            |= sourceLocationParser
            |= typeParser
            |= Parser.oneOf
                [ Parser.succeed identity
                    |. Parser.symbol (Token "(" ExpectedLeftParen)
                    |. noiseParser
                    |= Parser.loop [] typeMatchConditionParser
                    |. Parser.symbol (Token ")" ExpectedRightParen)
                , Parser.succeed []
                ]
            |= sourceLocationParser
            |. noiseParser
        , Parser.succeed (\startLoc sym endLoc -> TypeMatch (SourceLocationRange startLoc endLoc) (Type.Generic sym) [])
            |= sourceLocationParser
            |= genericParser
            |= sourceLocationParser
        , Parser.succeed (\startLoc typ endLoc -> TypeMatch (SourceLocationRange startLoc endLoc) typ [])
            |= sourceLocationParser
            |= typeRefParser
            |= 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



>
>
>



>


>


>





<

<
<









>
|




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

|
|




|
>
>
>



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







|




|







 







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







 







<







 







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







 







>
>
>
>
>
>
>
>
>
>







 







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







 







|




|


|
>





|
|

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



|

<
<
<
<
<
<
<
<
<

|
<
<
<


>
>
>
>
>
>
>
|










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


|

|







 







>
>
>

>
|





>
>
>
>
|
>
>
>


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







 







|
|







 







<
<
<
<
<
|








|
|
|
>
>
>
>
>






|
|
|
>
>
>
>
>





|
|
|
>
>
>
>
>







 







|
|



<




|
>
>
>











<
<
<
<

|



|
|

>
>
>
>
>
|
>
>
>
>







 







|
|



<




|
>
>
>







 







<
<
<







 







|







 







>
>
|







 







|
>
>













|








>
>
|







<
<


|
|











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







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

22


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
...
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
...
162
163
164
165
166
167
168

169
170
171
172
173
174
175
...
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
...
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
...
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
...
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447









448
449



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
...
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
...
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
...
693
694
695
696
697
698
699





700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
...
754
755
756
757
758
759
760
761
762
763
764
765

766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784




785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
...
815
816
817
818
819
820
821
822
823
824
825
826

827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
...
848
849
850
851
852
853
854



855
856
857
858
859
860
861
...
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
...
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
...
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
module Play.Parser exposing
    ( AST
    , AstNode(..)
    , ModuleDefinition(..)
    , ModuleDefinitionRec
    , PossiblyQualifiedType(..)
    , TypeDefinition(..)
    , TypeMatch(..)
    , TypeMatchValue(..)
    , TypeSignature(..)
    , WordDefinition
    , WordImplementation(..)
    , emptyModuleDefinition
    , run
    , typeDefinitionName
    , typeSignatureToMaybe
    )

import Dict exposing (Dict)
import Dict.Extra as Dict
import Parser.Advanced as Parser exposing ((|.), (|=), Token(..))

import Play.Data.SourceLocation exposing (SourceLocation, SourceLocationRange)


import Play.Parser.Problem exposing (..)
import Set exposing (Set)


type alias Parser a =
    Parser.Parser () Problem a


type alias AST =
    { moduleDefinition : ModuleDefinition
    , types : Dict String TypeDefinition
    , words : Dict String WordDefinition
    }


type ModuleDefinition
    = Undefined
    | Defined ModuleDefinitionRec


type alias ModuleDefinitionRec =
    { aliases : Dict String String
    , imports : Dict String (List String)
    , exposes : Set String
    }


type TypeDefinition
    = CustomTypeDef SourceLocationRange String (List String) (List ( String, PossiblyQualifiedType ))
    | UnionTypeDef SourceLocationRange String (List String) (List PossiblyQualifiedType)


type alias WordDefinition =
    { name : String
    , typeSignature : TypeSignature
    , sourceLocationRange : Maybe SourceLocationRange
    , aliases : Dict String String
    , imports : Dict String (List String)
    , implementation : WordImplementation
    }


type alias ParserWordType =
    { input : List PossiblyQualifiedType
    , output : List PossiblyQualifiedType
    }


type TypeSignature
    = NotProvided
    | UserProvided ParserWordType
    | Verified ParserWordType


typeSignatureToMaybe : TypeSignature -> Maybe ParserWordType
typeSignatureToMaybe ts =
    case ts of
        NotProvided ->
            Nothing

        UserProvided wt ->
            Just wt

        Verified wt ->
            Just wt


type PossiblyQualifiedType
    = LocalRef String (List PossiblyQualifiedType)
    | InternalRef (List String) String (List PossiblyQualifiedType)
    | ExternalRef (List String) String (List PossiblyQualifiedType)
    | Generic String
    | StackRange String
    | QuotationType ParserWordType


type WordImplementation
    = 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
    | Word SourceLocationRange String
    | PackageWord SourceLocationRange (List String) String
................................................................................
    Parser.run parser sourceCode
        |> Result.mapError (List.map .problem)



-- ATOMS


emptyModuleDefinition : ModuleDefinition
emptyModuleDefinition =
    Undefined


emptyModuleDefinitionRec : ModuleDefinitionRec
emptyModuleDefinitionRec =
    { aliases = Dict.empty
    , imports = Dict.empty
    , exposes = Set.empty
    }


validSymbolChar : Char -> Bool
validSymbolChar c =
    not <| Set.member c invalidSymbolChars


invalidSymbolChars : Set Char
................................................................................
        , '{'
        , '}'
        , '['
        , ']'
        , '('
        , ')'
        , '.'

        , '#'
        , '/'
        ]


whitespaceChars : Set Char
whitespaceChars =
................................................................................
                |. Parser.symbol (Token ":" NotMetadata)
                |> Parser.andThen (\_ -> Parser.problem FoundMetadata)
            , Parser.succeed identity
            ]
        |. noiseParser
        |> Parser.backtrackable


symbolParser2 : Parser String
symbolParser2 =
    Parser.variable
        { start = \c -> not (Char.isDigit c || Char.isUpper c || Set.member c invalidSymbolChars)
        , inner = validSymbolChar
        , reserved = Set.empty
        , expecting = NotSymbol
        }
        |. Parser.oneOf
            [ Parser.succeed identity
                |. Parser.symbol (Token ":" NotMetadata)
                |> Parser.andThen (\_ -> Parser.problem FoundMetadata)
            , Parser.succeed identity
            ]
        |> Parser.backtrackable


symbolImplParser : Parser String
symbolImplParser =
    Parser.variable
        { start = \c -> not (Char.isDigit c || Set.member c invalidSymbolChars)
        , inner = validSymbolChar
        , reserved = Set.empty
................................................................................
            [ Parser.succeed identity
                |. Parser.symbol (Token ":" NotMetadata)
                |> Parser.andThen (\_ -> Parser.problem FoundMetadata)
            , Parser.succeed identity
            ]
        |> Parser.backtrackable


symbolImplListParser : List String -> Parser (Parser.Step (List String) (List String))
symbolImplListParser symbols =
    Parser.oneOf
        [ Parser.succeed (\sym -> Parser.Loop (sym :: symbols))
            |= symbolImplParser
            |. noiseParser
        , Parser.succeed (Parser.Done <| List.reverse symbols)
        ]


symbolImplParser2 : Parser (SourceLocationRange -> AstNode)
symbolImplParser2 =
    let
        externalBuilder firstSymbol (( partialPath, reference ) as modulePathResult) =
            let
                path =
................................................................................
                [ Parser.loop [] modulePathParser
                , Parser.succeed ( [], "" )
                ]
        ]
        |. noiseParser
        |> Parser.andThen identity


modulePathStringParser : Parser String
modulePathStringParser =
    Parser.oneOf
        [ Parser.succeed identity
            |= symbolImplParser
            |> Parser.andThen (\sym -> Parser.loop sym moduleRefParser)
        , Parser.succeed identity
            |= Parser.loop "" moduleRefParser
        ]


moduleRefParser : String -> Parser (Parser.Step String String)
moduleRefParser path =
    Parser.oneOf
        [ Parser.succeed (\part -> Parser.Loop (path ++ "/" ++ part))
            |. Parser.symbol (Token "/" NotMetadata)
            |= symbolImplParser
        , Parser.succeed (Parser.Done path)
        ]


modulePathParser : List String -> Parser (Parser.Step (List String) ( List String, String ))
modulePathParser symbols =
    Parser.oneOf
        [ Parser.succeed (\name -> Parser.Loop (name :: symbols))
            |. Parser.symbol (Token "/" NotMetadata)
            |= symbolImplParser
................................................................................
        , inner = validSymbolChar
        , reserved = Set.empty
        , expecting = NotType
        }
        |. noiseParser


genericOrRangeParser : Parser PossiblyQualifiedType
genericOrRangeParser =
    let
        helper value =
            Parser.oneOf
                [ Parser.succeed (StackRange value)
                    |. Parser.symbol (Token "..." NoProblem)
                    |. noiseParser
                , Parser.succeed (Generic value)
                    |. Parser.chompIf (\c -> Set.member c whitespaceChars) NoProblem
                ]
    in
    Parser.andThen helper genericParser


typeSignatureRefParser : Parser PossiblyQualifiedType
typeSignatureRefParser =
    Parser.oneOf
        [ Parser.succeed (\name -> LocalRef name [])
            |= typeNameParser
        , Parser.succeed (\( path, name ) -> ExternalRef path name [])
            |. Parser.symbol (Token "/" NoProblem)
            |= Parser.loop [] modularizedTypeRefParser
        , Parser.succeed (\( path, name ) -> InternalRef path name [])
            |= Parser.loop [] modularizedTypeRefParser
        , Parser.succeed Generic
            |= genericParser
        , Parser.succeed identity
            |. Parser.symbol (Token "(" ExpectedLeftParen)
            |. noiseParser
            |= typeRefParser
            |. Parser.symbol (Token ")" ExpectedRightParen)
            |. noiseParser
        ]


typeRefParser : Parser PossiblyQualifiedType
typeRefParser =









    Parser.oneOf
        [ Parser.succeed LocalRef



            |= typeNameParser
            |= Parser.loop [] typeOrGenericParser
        , Parser.succeed (\( path, name ) binds -> ExternalRef path name binds)
            |. Parser.symbol (Token "/" NoProblem)
            |= Parser.loop [] modularizedTypeRefParser
            |= Parser.loop [] typeOrGenericParser
        , Parser.succeed (\( path, name ) binds -> InternalRef path name binds)
            |= Parser.loop [] modularizedTypeRefParser
            |= Parser.loop [] typeOrGenericParser
        , Parser.succeed Generic
            |= genericParser
        , Parser.succeed identity
            |. Parser.symbol (Token "(" ExpectedLeftParen)
            |. noiseParser
            |= Parser.lazy (\_ -> typeRefParser)
            |. Parser.symbol (Token ")" ExpectedRightParen)
            |. noiseParser
        ]


typeMatchTypeParser : Parser PossiblyQualifiedType
typeMatchTypeParser =
    Parser.oneOf
        [ Parser.succeed (\name -> LocalRef name [])
            |= typeNameParser
        , Parser.succeed (\( path, name ) -> ExternalRef path name [])
            |. Parser.symbol (Token "/" NoProblem)
            |= Parser.loop [] modularizedTypeRefParser
        , Parser.succeed (\( path, name ) -> InternalRef path name [])
            |= Parser.loop [] modularizedTypeRefParser
        , Parser.succeed Generic
            |= genericParser
        , Parser.succeed identity
            |. Parser.symbol (Token "(" ExpectedLeftParen)
            |. noiseParser
            |= typeRefParser
            |. Parser.symbol (Token ")" ExpectedRightParen)
            |. noiseParser
        ]


modularizedTypeRefParser :
    List String
    -> Parser (Parser.Step (List String) ( List String, String ))
modularizedTypeRefParser reversedPath =
    let
        onType type_ =
            Parser.Done
                ( List.reverse reversedPath
                , type_
                )

        addToPath pathPiece =
            Parser.Loop (pathPiece :: reversedPath)
    in
    Parser.oneOf
        [ Parser.succeed onType
            |= typeNameParser
        , Parser.succeed addToPath
            |= symbolParser2
            |. Parser.symbol (Token "/" NoProblem)
        ]


typeOrGenericParser : List PossiblyQualifiedType -> Parser (Parser.Step (List PossiblyQualifiedType) (List PossiblyQualifiedType))
typeOrGenericParser types =
    Parser.oneOf
        [ Parser.succeed (\name -> Parser.Loop (LocalRef name [] :: types))
            |= typeNameParser
        , Parser.succeed (\name -> Parser.Loop (Generic name :: types))
            |= genericParser
        , Parser.succeed (Parser.Done (List.reverse types))
        ]


noiseParser : Parser ()
noiseParser =
................................................................................

-- Grammar


parser : Parser AST
parser =
    let
        joinParseResults modDef ast =
            { ast | moduleDefinition = modDef }

        emptyAst =
            { moduleDefinition = emptyModuleDefinition
            , types = Dict.empty
            , words = Dict.empty
            }
    in
    Parser.succeed identity
        |. noiseParser
        |= Parser.oneOf
            [ Parser.succeed joinParseResults
                |= moduleDefinitionParser
                |. noiseParser
                |= Parser.loop emptyAst definitionParser
            , Parser.succeed (joinParseResults emptyModuleDefinition)
                |= Parser.loop emptyAst definitionParser
            ]
        |. Parser.end ExpectedEnd


moduleDefinitionParser : Parser ModuleDefinition
moduleDefinitionParser =
    Parser.succeed identity
        |. Parser.keyword (Token "defmodule:" NoProblem)
        |. noiseParser
        |= Parser.map Defined (Parser.loop emptyModuleDefinitionRec moduleDefinitionMetaParser)


moduleDefinitionMetaParser : ModuleDefinitionRec -> Parser (Parser.Step ModuleDefinitionRec ModuleDefinitionRec)
moduleDefinitionMetaParser def =
    Parser.oneOf
        [ Parser.succeed (\alias value -> Parser.Loop { def | aliases = Dict.insert alias value def.aliases })
            |. Parser.keyword (Token "alias:" NoProblem)
            |. noiseParser
            |= symbolParser
            |. noiseParser
            |= modulePathStringParser
            |. noiseParser
        , Parser.succeed (\mod vals -> Parser.Loop { def | imports = Dict.insert mod vals def.imports })
            |. Parser.keyword (Token "import:" NoProblem)
            |. noiseParser
            |= modulePathStringParser
            |. noiseParser
            |= Parser.loop [] symbolImplListParser
            |. noiseParser
        , Parser.succeed (\exposings -> Parser.Loop { def | exposes = exposings })
            |. Parser.keyword (Token "exposing:" NoProblem)
            |. noiseParser
            |= (Parser.loop [] symbolImplListParser |> Parser.map Set.fromList)
            |. noiseParser
        , Parser.succeed UnknownMetadata
            |= definitionMetadataParser
            |> Parser.andThen Parser.problem
        , Parser.succeed (Parser.Done def)
            |. Parser.keyword (Token ":" NoProblem)
            |. noiseParser
        ]


definitionParser : AST -> Parser (Parser.Step AST AST)
definitionParser ast =
    let
        insertWord wordDef =
            case maybeInsertWordProblem wordDef of
                Just problem ->
................................................................................
                        |> Parser.succeed

        maybeInsertWordProblem wordDef =
            Dict.get wordDef.name ast.words
                |> Maybe.map
                    (\prevDef ->
                        WordAlreadyDefined wordDef.name
                            prevDef.sourceLocationRange
                            wordDef.sourceLocationRange
                    )

        insertType typeDef =
            let
                typeName =
                    typeDefinitionName typeDef
            in
................................................................................
    case typeDef of
        UnionTypeDef _ _ _ _ ->
            []

        CustomTypeDef _ typeName binds typeMembers ->
            let
                typeOfType =





                    LocalRef typeName (List.map Generic binds)

                ctorDef =
                    { name =
                        if List.isEmpty typeMembers then
                            typeName

                        else
                            ">" ++ typeName
                    , typeSignature =
                        Verified
                            { input = List.map Tuple.second typeMembers
                            , output = [ typeOfType ]
                            }
                    , sourceLocationRange = Nothing
                    , aliases = Dict.empty
                    , imports = Dict.empty
                    , implementation =
                        SoloImpl [ ConstructType typeName ]
                    }

                setterGetterPair ( memberName, memberType ) =
                    [ { name = ">" ++ memberName
                      , typeSignature =
                            Verified
                                { input = [ typeOfType, memberType ]
                                , output = [ typeOfType ]
                                }
                      , sourceLocationRange = Nothing
                      , aliases = Dict.empty
                      , imports = Dict.empty
                      , implementation =
                            SoloImpl
                                [ SetMember typeName memberName ]
                      }
                    , { name = memberName ++ ">"
                      , typeSignature =
                            Verified
                                { input = [ typeOfType ]
                                , output = [ memberType ]
                                }
                      , sourceLocationRange = Nothing
                      , aliases = Dict.empty
                      , imports = Dict.empty
                      , implementation =
                            SoloImpl
                                [ GetMember typeName memberName ]
                      }
                    ]
            in
            typeMembers
................................................................................

wordDefinitionParser : SourceLocation -> Parser WordDefinition
wordDefinitionParser startLocation =
    let
        joinParseResults name def endLocation =
            { def
                | name = name
                , sourceLocationRange =
                    Just
                        { start = startLocation
                        , end = endLocation
                        }

            }

        emptyDef =
            { name = ""
            , typeSignature = NotProvided
            , sourceLocationRange = Nothing
            , aliases = Dict.empty
            , imports = Dict.empty
            , implementation = SoloImpl []
            }
    in
    Parser.succeed joinParseResults
        |= symbolParser
        |= Parser.loop emptyDef wordMetadataParser
        |= sourceLocationParser


wordMetadataParser : WordDefinition -> Parser (Parser.Step WordDefinition WordDefinition)
wordMetadataParser def =




    Parser.oneOf
        [ Parser.succeed (\typeSign -> Parser.Loop { def | typeSignature = UserProvided typeSign })
            |. Parser.keyword (Token "type:" NoProblem)
            |. noiseParser
            |= typeSignatureParser
        , Parser.succeed (\alias value -> Parser.Loop { def | aliases = Dict.insert alias value def.aliases })
            |. Parser.keyword (Token "alias:" NoProblem)
            |. noiseParser
            |= symbolParser
            |. noiseParser
            |= modulePathStringParser
            |. noiseParser
        , Parser.succeed (\mod vals -> Parser.Loop { def | imports = Dict.insert mod vals def.imports })
            |. Parser.keyword (Token "import:" NoProblem)
            |. noiseParser
            |= modulePathStringParser
            |. noiseParser
            |= Parser.loop [] symbolImplListParser
            |. noiseParser
        , Parser.succeed (\impl -> Parser.Loop { def | implementation = SoloImpl impl })
            |. Parser.keyword (Token ":" NoProblem)
            |. noiseParser
            |= implementationParser
        , Parser.succeed UnknownMetadata
            |= definitionMetadataParser
................................................................................
multiWordDefinitionParser : SourceLocation -> Parser WordDefinition
multiWordDefinitionParser startLocation =
    let
        joinParseResults name def endLocation =
            reverseWhens <|
                { def
                    | name = name
                    , sourceLocationRange =
                        Just
                            { start = startLocation
                            , end = endLocation
                            }

                }

        emptyDef =
            { name = ""
            , typeSignature = NotProvided
            , sourceLocationRange = Nothing
            , aliases = Dict.empty
            , imports = Dict.empty
            , implementation = SoloImpl []
            }

        reverseWhens def =
            case def.implementation of
                SoloImpl _ ->
                    def
................................................................................
        |= Parser.loop emptyDef multiWordMetadataParser
        |= sourceLocationParser


multiWordMetadataParser : WordDefinition -> Parser (Parser.Step WordDefinition WordDefinition)
multiWordMetadataParser def =
    let



        addWhenImpl impl =
            case def.implementation of
                MultiImpl whens default ->
                    MultiImpl (impl :: whens) default

                SoloImpl default ->
                    MultiImpl [ impl ] default
................................................................................
                MultiImpl whens _ ->
                    MultiImpl whens impl

                SoloImpl _ ->
                    MultiImpl [] impl
    in
    Parser.oneOf
        [ Parser.succeed (\typeSign -> Parser.Loop { def | typeSignature = UserProvided typeSign })
            |. Parser.keyword (Token "type:" NoProblem)
            |. noiseParser
            |= typeSignatureParser
        , Parser.succeed (\impl -> Parser.Loop { def | implementation = setDefaultImpl impl })
            |. Parser.keyword (Token "else:" NoProblem)
            |. noiseParser
            |= implementationParser
................................................................................
    Parser.oneOf
        [ Parser.succeed (\name -> Parser.Loop (name :: generics))
            |= genericParser
        , Parser.succeed (Parser.Done (List.reverse generics))
        ]


typeMemberParser :
    List ( String, PossiblyQualifiedType )
    -> Parser (Parser.Step (List ( String, PossiblyQualifiedType )) (List ( String, PossiblyQualifiedType )))
typeMemberParser types =
    Parser.oneOf
        [ Parser.succeed (\name type_ -> Parser.Loop (( name, type_ ) :: types))
            |. Parser.symbol (Token ":" NoProblem)
            |. noiseParser
            |= symbolParser
            |= typeRefParser
................................................................................
    Parser.succeed ctor
        |= typeNameParser
        |= Parser.loop [] typeGenericParser
        |= Parser.loop [] unionTypeMemberParser
        |= sourceLocationParser


unionTypeMemberParser :
    List PossiblyQualifiedType
    -> Parser (Parser.Step (List PossiblyQualifiedType) (List PossiblyQualifiedType))
unionTypeMemberParser types =
    Parser.oneOf
        [ Parser.succeed (\type_ -> Parser.Loop (type_ :: types))
            |. Parser.symbol (Token ":" NoProblem)
            |. noiseParser
            |= typeRefParser
        , Parser.succeed UnknownMetadata
            |= definitionMetadataParser
            |> Parser.andThen Parser.problem
        , Parser.succeed (Parser.Done (List.reverse types))
        ]


typeSignatureParser : Parser ParserWordType
typeSignatureParser =
    Parser.succeed (\input output -> { input = input, output = output })
        |= Parser.loop [] typeLoopParser
        |. Parser.symbol (Token "--" ExpectedTypeSeperator)
        |. noiseParser
        |= Parser.loop [] typeLoopParser


typeLoopParser :
    List PossiblyQualifiedType
    -> Parser (Parser.Step (List PossiblyQualifiedType) (List PossiblyQualifiedType))
typeLoopParser reverseTypes =
    let
        step type_ =
            Parser.Loop (type_ :: reverseTypes)
    in
    Parser.oneOf
        [ Parser.succeed step


            |= genericOrRangeParser
        , Parser.succeed step
            |= typeSignatureRefParser
        , Parser.succeed (\wordType -> step (QuotationType wordType))
            |. Parser.symbol (Token "[" ExpectedLeftBracket)
            |. noiseParser
            |= typeSignatureParser
            |. Parser.symbol (Token "]" ExpectedRightBracket)
            |. 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
        |. noiseParser











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

Modified src/Play/Qualifier.elm from [9fd8ef35a0] to [0a582ab702].

1
2
3

4
5
6
7
8
9
10
..
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

31
32
33
34
35
36
37
38
39
..
59
60
61
62
63
64
65






66
67
68
69
70
71
72
..
82
83
84
85
86
87
88

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125































126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
...
176
177
178
179
180
181
182











183
184
185
186
187
188
189
190
191
192
193



194
195
196
197
198
199
200
...
203
204
205
206
207
208
209
210








211
212
213
214
215
216
217



218
219
220
221
222
223
224
225
226
227
228
229
230






231

232
233




234
















































235









236
237




238
239
240
241
242
243
244
245
246
247










248

249



250
251

252





















































253






















254



255
256







257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272








273
274
275







276



277
278

279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
...
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323


324


325
326
327
328



















329
330

331
332
333

334
335
336
337





338


339
340
341
342
343


344
345





346
347

348
349







350
351
352
353
354
355
356
...
389
390
391
392
393
394
395

396
397
398
399
400
401
402

403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454








455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472



473
474
475
476
477
478
479
480




481










































































482
483
484
485
486
487
488

489
490
491
492
493
494
495
496
497
498
499
500






501
502



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517


518
519
520
521



522

523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542





543

544
545
546
547
548
549
550
551
...
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
...
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
...
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
...
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682















































































































































































































































































module Play.Qualifier exposing (..)

import Dict exposing (Dict)

import Play.Data.Builtin as Builtin exposing (Builtin)
import Play.Data.Metadata as Metadata exposing (Metadata)
import Play.Data.SourceLocation as SourceLocation exposing (SourceLocationRange)
import Play.Data.Type as Type exposing (Type, WordType)
import Play.Data.TypeSignature as TypeSignature
import Play.Parser as Parser
import Play.Qualifier.Problem exposing (Problem(..))
................................................................................
import Result.Extra as Result
import Set exposing (Set)


type alias AST =
    { types : Dict String TypeDefinition
    , words : Dict String WordDefinition
    , additionalModulesRequired : Set String
    , checkForExistingTypes : Set String
    , checkForExistingWords : Set String
    }


type alias ExposedAST =
    { types : Dict String TypeDefinition
    , words : Dict String WordDefinition
    }


type TypeDefinition

    = CustomTypeDef String SourceLocationRange (List String) (List ( String, Type ))
    | UnionTypeDef String SourceLocationRange (List String) (List Type)


type alias WordDefinition =
    { name : String
    , metadata : Metadata
    , implementation : WordImplementation
    }
................................................................................
    | Word SourceLocationRange String
    | WordRef SourceLocationRange String
    | ConstructType String
    | GetMember String String
    | SetMember String String
    | Builtin SourceLocationRange Builtin








builtinDict : Dict String Builtin
builtinDict =
    Dict.fromList
        [ ( "+", Builtin.Plus )
        , ( "-", Builtin.Minus )
        , ( "*", Builtin.Multiply )
................................................................................


type alias RunConfig =
    { packageName : String
    , modulePath : String
    , ast : Parser.AST
    , externalModules : Dict String String

    }


run : RunConfig -> Result (List Problem) AST
run config =
    let
        ( typeErrors, qualifiedTypes ) =
            Dict.foldl (\_ val acc -> qualifyType config val acc) ( [], Dict.empty ) config.ast.types
                |> Tuple.mapSecond (\qt -> Dict.map (\_ v -> resolveUnionInTypeDefs qt v) qt)

        ( wordErrors, externalWords, qualifiedWords ) =
            Dict.foldl (\_ val acc -> qualifyDefinition config qualifiedTypes val acc) ( [], Set.empty, Dict.empty ) config.ast.words

        requiredModules =
            Set.toList externalWords
                |> List.map Tuple.first
                |> Set.fromList

        wordsToCheck =
            Set.toList externalWords
                |> List.map (\( path, name ) -> path ++ "/" ++ name)
                |> Set.fromList
    in
    case ( typeErrors, wordErrors ) of
        ( [], [] ) ->
            Ok
                { types = qualifiedTypes
                , words = qualifiedWords
                , additionalModulesRequired = requiredModules
                , checkForExistingTypes = Set.empty
                , checkForExistingWords = wordsToCheck
                }

        _ ->
            Err <| typeErrors ++ wordErrors

































resolveUnionInTypeDefs : Dict String TypeDefinition -> TypeDefinition -> TypeDefinition
resolveUnionInTypeDefs qt td =
    case td of
        CustomTypeDef name range generics members ->
            CustomTypeDef name range generics (List.map (Tuple.mapSecond (resolveUnion qt)) members)

        UnionTypeDef name range generics memberTypes ->
            UnionTypeDef name range generics (List.map (resolveUnion qt) memberTypes)


resolveUnion : Dict String TypeDefinition -> Type -> Type
resolveUnion typeDefs type_ =
    case type_ of
        Type.Custom typeName ->
            case Dict.get typeName typeDefs of
                Just (UnionTypeDef _ _ _ members) ->
                    Type.Union members

                _ ->
                    type_

        Type.CustomGeneric typeName types ->
            case Dict.get typeName typeDefs of
                Just (UnionTypeDef _ _ generics members) ->
                    let
                        genericsMap =
                            List.map2 Tuple.pair generics types
                                |> Dict.fromList

                        rebindGenerics t =
                            case t of
................................................................................

qualifyType :
    RunConfig
    -> Parser.TypeDefinition
    -> ( List Problem, Dict String TypeDefinition )
    -> ( List Problem, Dict String TypeDefinition )
qualifyType config typeDef ( errors, acc ) =











    case typeDef of
        Parser.CustomTypeDef range name generics members ->
            let
                qualifiedName =
                    qualifyName config name

                qualifiedMemberResult =
                    List.map (Tuple.mapSecond (qualifyMemberType config range)) members
                        |> List.map raiseTupleError
                        |> Result.combine




                raiseTupleError ( label, result ) =
                    case result of
                        Ok value ->
                            Ok ( label, value )

                        Err err ->
                            Err err
................................................................................
                Err err ->
                    ( err :: errors
                    , acc
                    )

                Ok qualifiedMembers ->
                    ( errors
                    , Dict.insert qualifiedName (CustomTypeDef qualifiedName range generics qualifiedMembers) acc








                    )

        Parser.UnionTypeDef range name generics memberTypes ->
            let
                qualifiedName =
                    qualifyName config name




                qualifiedMemberTypesResult =
                    List.map (qualifyMemberType config range) memberTypes
                        |> Result.combine
            in
            case qualifiedMemberTypesResult of
                Err err ->
                    ( err :: errors
                    , acc
                    )

                Ok qualifiedMemberTypes ->
                    ( errors
                    , Dict.insert qualifiedName (UnionTypeDef qualifiedName range generics qualifiedMemberTypes) acc






                    )







qualifyMemberType : RunConfig -> SourceLocationRange -> Type -> Result Problem Type
















































qualifyMemberType config range type_ =









    case type_ of
        Type.Custom name ->




            case Dict.get name config.ast.types of
                Just _ ->
                    Ok <| Type.Custom (qualifyName config name)

                Nothing ->
                    Err <| UnknownTypeRef range name

        Type.CustomGeneric name binds ->
            case Dict.get name config.ast.types of
                Just _ ->










                    Ok <| Type.CustomGeneric (qualifyName config name) binds





                Nothing ->
                    Err <| UnknownTypeRef range name























































        _ ->






















            Ok type_












qualifyDefinition :
    RunConfig
    -> Dict String TypeDefinition
    -> Parser.WordDefinition
    -> ( List Problem, Set ( String, String ), Dict String WordDefinition )
    -> ( List Problem, Set ( String, String ), Dict String WordDefinition )
qualifyDefinition config qualifiedTypes unqualifiedWord ( errors, externalWords, acc ) =
    let
        ( whens, impl ) =
            case unqualifiedWord.implementation of
                Parser.SoloImpl defImpl ->
                    ( [], defImpl )

                Parser.MultiImpl whenImpl defImpl ->
                    ( whenImpl, defImpl )









        ( newWordsAfterWhens, externalWordsAfterWhens, qualifiedWhensResult ) =
            List.foldr (qualifyWhen config qualifiedTypes unqualifiedWord.name) ( acc, Set.empty, [] ) whens
                |> (\( a, b, nodes ) -> ( a, b, Result.combine nodes ))











        ( newWordsAfterImpl, externalWordsAfterImpl, qualifiedImplementationResult ) =
            initQualifyNode unqualifiedWord.name config newWordsAfterWhens impl


        qualifiedMetadataResult =
            qualifyMetadata config qualifiedTypes unqualifiedWord.metadata

        qualifiedName =
            qualifyName config unqualifiedWord.name
    in
    case ( qualifiedWhensResult, qualifiedImplementationResult, qualifiedMetadataResult ) of
        ( Ok qualifiedWhens, Ok qualifiedImplementation, Ok qualifiedMetadata ) ->
            ( errors
            , externalWords
                |> Set.union externalWordsAfterWhens
                |> Set.union externalWordsAfterImpl
            , Dict.insert qualifiedName
                { name = qualifiedName
                , metadata = qualifiedMetadata
                , implementation =
                    if List.isEmpty qualifiedWhens then
                        SoloImpl qualifiedImplementation

................................................................................
                        MultiImpl qualifiedWhens qualifiedImplementation
                }
                newWordsAfterImpl
            )

        ( Err whenError, _, _ ) ->
            ( whenError :: errors
            , externalWords
            , newWordsAfterImpl
            )

        ( _, Err implError, _ ) ->
            ( implError :: errors
            , externalWords
            , newWordsAfterImpl
            )

        ( _, _, Err metaError ) ->
            ( metaError :: errors
            , externalWords
            , newWordsAfterImpl
            )




qualifyMetadata : RunConfig -> Dict String TypeDefinition -> Metadata -> Result Problem Metadata


qualifyMetadata config qualifiedTypes meta =
    let
        wordRange =
            Maybe.withDefault SourceLocation.emptyRange meta.sourceLocationRange



















    in
    TypeSignature.toMaybe meta.type_

        |> Maybe.map (\ts -> ts.input ++ ts.output)
        |> Maybe.withDefault []
        |> List.map (validateTypeReferences config qualifiedTypes wordRange)

        |> Result.combine
        |> Result.map
            (\qualifiedFlatTypeSignature ->
                let





                    ts =


                        TypeSignature.map
                            (\wt ->
                                { input = List.take (List.length wt.input) qualifiedFlatTypeSignature
                                , output = List.drop (List.length wt.input) qualifiedFlatTypeSignature
                                }


                            )
                            meta.type_





                in
                { meta

                    | type_ =
                        TypeSignature.map (resolveUnions qualifiedTypes) ts







                }
            )


validateTypeReferences : RunConfig -> Dict String TypeDefinition -> SourceLocationRange -> Type -> Result Problem Type
validateTypeReferences config typeDefs wordRange type_ =
    case type_ of
................................................................................
    }


qualifyWhen :
    RunConfig
    -> Dict String TypeDefinition
    -> String

    -> ( Parser.TypeMatch, List Parser.AstNode )
    -> ( Dict String WordDefinition, Set ( String, String ), List (Result Problem ( TypeMatch, List Node )) )
    -> ( Dict String WordDefinition, Set ( String, String ), List (Result Problem ( TypeMatch, List Node )) )
qualifyWhen config qualifiedTypes wordName ( typeMatch, impl ) ( qualifiedWords, externalWords, result ) =
    let
        ( newWords, externalWordsAfterImpl, qualifiedImplementationResult ) =
            initQualifyNode wordName config qualifiedWords impl


        qualifiedMatchResult =
            qualifyMatch config qualifiedTypes typeMatch
    in
    case ( qualifiedImplementationResult, qualifiedMatchResult ) of
        ( Err err, _ ) ->
            ( newWords
            , externalWords
            , Err err :: result
            )

        ( _, Err err ) ->
            ( newWords
            , externalWords
            , Err err :: result
            )

        ( Ok qualifiedImplementation, Ok qualifiedMatch ) ->
            ( newWords
            , Set.union externalWords externalWordsAfterImpl
            , Ok ( qualifiedMatch, qualifiedImplementation ) :: result
            )


qualifyMatch : RunConfig -> Dict String TypeDefinition -> Parser.TypeMatch -> Result Problem TypeMatch
qualifyMatch config qualifiedTypes typeMatch =
    case typeMatch of
        Parser.TypeMatch range Type.Int [] ->
            Ok <| TypeMatch range Type.Int []

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

        Parser.TypeMatch range ((Type.Generic _) as type_) [] ->
            Ok <| TypeMatch range type_ []

        Parser.TypeMatch range (Type.Custom name) patterns ->
            let
                qualifiedName =
                    qualifyName config name
            in
            case Dict.get qualifiedName qualifiedTypes of
                Just (CustomTypeDef _ _ gens members) ->
                    let
                        memberNames =
                            members
                                |> List.map Tuple.first
                                |> Set.fromList

                        qualifiedPatternsResult =
                            patterns
                                |> List.map (qualifyMatchValue config qualifiedTypes range qualifiedName memberNames)








                                |> Result.combine

                        actualType =
                            case gens of
                                [] ->
                                    Type.Custom qualifiedName

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

                        Err err ->
                            Err err

                Just (UnionTypeDef _ _ _ types) ->



                    if List.isEmpty patterns then
                        Ok <| TypeMatch range (Type.Union types) []

                    else
                        Err <| UnionTypeMatchWithPatterns range

                Nothing ->
                    Err <| UnknownTypeRef range qualifiedName















































































        Parser.TypeMatch range _ _ ->
            Err <| InvalidTypeMatch range


qualifyMatchValue :
    RunConfig
    -> Dict String TypeDefinition

    -> SourceLocationRange
    -> String
    -> Set String
    -> ( String, Parser.TypeMatchValue )
    -> Result Problem ( String, TypeMatchValue )
qualifyMatchValue config qualifiedTypes range typeName memberNames ( fieldName, matchValue ) =
    if Set.member fieldName memberNames then
        case matchValue of
            Parser.LiteralInt val ->
                Ok <| ( fieldName, LiteralInt val )

            Parser.LiteralType type_ ->






                Ok <| ( fieldName, LiteralType type_ )




            Parser.RecursiveMatch typeMatch ->
                case qualifyMatch config qualifiedTypes typeMatch of
                    Err err ->
                        Err err

                    Ok match ->
                        Ok <| ( fieldName, RecursiveMatch match )

    else
        Err <| NoSuchMemberOnType range typeName fieldName


initQualifyNode :
    String
    -> RunConfig


    -> Dict String WordDefinition
    -> List Parser.AstNode
    -> ( Dict String WordDefinition, Set ( String, String ), Result Problem (List Node) )
initQualifyNode currentDefName config qualifiedWords impl =



    List.foldr (qualifyNode config currentDefName) (initQualifyNodeAccumulator qualifiedWords) impl

        |> (\acc -> ( acc.qualifiedWords, acc.externalWords, Result.combine acc.qualifiedNodes ))


type alias QualifyNodeAccumulator =
    { availableQuoteId : Int
    , qualifiedWords : Dict String WordDefinition
    , qualifiedNodes : List (Result Problem Node)
    , externalWords : Set ( String, String )
    }


initQualifyNodeAccumulator : Dict String WordDefinition -> QualifyNodeAccumulator
initQualifyNodeAccumulator qualifiedWords =
    { availableQuoteId = 1
    , qualifiedWords = qualifiedWords
    , qualifiedNodes = []
    , externalWords = Set.empty
    }







qualifyNode : RunConfig -> String -> Parser.AstNode -> QualifyNodeAccumulator -> QualifyNodeAccumulator

qualifyNode config currentDefName node acc =
    case node of
        Parser.Integer loc value ->
            { acc | qualifiedNodes = Ok (Integer loc value) :: acc.qualifiedNodes }

        Parser.Word loc value ->
            let
                qualifiedName =
................................................................................

            else
                case Dict.get value builtinDict of
                    Just builtin ->
                        { acc | qualifiedNodes = Ok (Builtin loc builtin) :: acc.qualifiedNodes }

                    Nothing ->


                        { acc | qualifiedNodes = Err (UnknownWordRef loc value) :: acc.qualifiedNodes }




























        Parser.PackageWord loc path value ->
            let
                normalizedPath =
                    String.join "/" path

















                qualifiedPath =
                    qualifyPackageModule config normalizedPath

                qualifiedName =
                    String.join "/" [ qualifiedPath, value ]



            in
            { acc






                | qualifiedNodes = Ok (Word loc qualifiedName) :: acc.qualifiedNodes
                , externalWords = Set.insert ( qualifiedPath, value ) acc.externalWords
            }



        Parser.ExternalWord loc path value ->
            let
                normalizedPath =
                    "/" ++ String.join "/" path
            in
            case Dict.get normalizedPath config.externalModules of
                Nothing ->
                    { acc | qualifiedNodes = Err (UnknownWordRef loc (normalizedPath ++ "/" ++ value)) :: acc.qualifiedNodes }

                Just package ->
                    let
                        qualifiedPath =



                            "/" ++ package ++ normalizedPath



                        fullReference =
                            qualifiedPath ++ "/" ++ value
                    in
                    { acc






                        | qualifiedNodes = Ok (Word loc fullReference) :: acc.qualifiedNodes
                        , externalWords = Set.insert ( qualifiedPath, value ) acc.externalWords
                    }



        Parser.ConstructType typeName ->
            { acc | qualifiedNodes = Ok (ConstructType (qualifyName config typeName)) :: acc.qualifiedNodes }

        Parser.SetMember typeName memberName ->
            { acc | qualifiedNodes = Ok (SetMember (qualifyName config typeName) memberName) :: acc.qualifiedNodes }

................................................................................
                quoteName =
                    if String.startsWith "quote:" currentDefName then
                        currentDefName ++ "/" ++ String.fromInt acc.availableQuoteId

                    else
                        "quote:" ++ qualifyName config currentDefName ++ "/" ++ String.fromInt acc.availableQuoteId

                ( newWordsAfterQuot, externalWords, qualifiedQuotImplResult ) =
                    initQualifyNode quoteName config acc.qualifiedWords quotImpl
            in
            case qualifiedQuotImplResult of
                Ok qualifiedQuotImpl ->
                    { acc
                        | availableQuoteId = acc.availableQuoteId + 1
                        , qualifiedWords =
                            Dict.insert quoteName
................................................................................
                                , metadata =
                                    Metadata.default
                                        |> Metadata.isQuoted
                                , implementation = SoloImpl qualifiedQuotImpl
                                }
                                newWordsAfterQuot
                        , qualifiedNodes = Ok (WordRef sourceLocation quoteName) :: acc.qualifiedNodes
                        , externalWords = Set.union externalWords acc.externalWords
                    }

                Err err ->
                    { acc | qualifiedNodes = Err err :: acc.qualifiedNodes }


typeDefinitionName : TypeDefinition -> String
typeDefinitionName typeDef =
    case typeDef of
        CustomTypeDef name _ _ _ ->
            name

        UnionTypeDef name _ _ _ ->
            name


qualifyName : RunConfig -> String -> String
qualifyName config name =
    if config.packageName == "" then
        name
................................................................................
            , "/"
            , config.modulePath
            , "/"
            , name
            ]


qualifyPackageModule : RunConfig -> String -> String
qualifyPackageModule config path =
    if config.packageName == "" then
        path

    else
        String.concat
            [ "/"
            , config.packageName
            , "/"
            , path
            ]


















































































































































































































































































>







 







<
<
<



|
<
<
<
<
<
|
>
|
|







 







>
>
>
>
>
>







 







>










|
|

|
|
<
<
<
<
<
<
<






<
<
<






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



|
|

|
|







|







|







 







>
>
>
>
>
>
>
>
>
>
>







|



>
>
>







 







|
>
>
>
>
>
>
>
>







>
>
>

|










|
>
>
>
>
>
>
|
>
|

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

<
>
>
>
>





|

|


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

>
>
>

<
>

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

>
>
>
>
>
>
>




|
|
|









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


|







<
<
<







 







<





<





<




>
>
|
>
>
|


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

<
>


<
>




>
>
>
>
>

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

<
>


>
>
>
>
>
>
>







 







>

|
|
|

|
<
>


|




<





<





<




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








|
>
>
>
>
>
>
>
>





|


|








|
>
>
>







|
>
>
>
>

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







>





|






>
>
>
>
>
>
|

>
>
>

|











<
|
>
>


|
<
>
>
>
|
>
|






<








<



>
>
>
>
>
|
>
|







 







>
>
|

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


|


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

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












|
>
>
>
|
>
>
|
<
<

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







 







|
|







 







<









|


|







 







|
|
|





|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
..
12
13
14
15
16
17
18



19
20
21
22





23
24
25
26
27
28
29
30
31
32
33
..
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
..
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104







105
106
107
108
109
110



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
...
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
...
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351

352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382

383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498


499
500
501
502
503
504
505
506
507
508
509
510

511
512
513
514
515
516
517
518
519
520
521



522
523
524
525
526
527
528
...
530
531
532
533
534
535
536

537
538
539
540
541

542
543
544
545
546

547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579

580
581
582

583
584
585
586
587
588
589
590
591
592
593
594
595
596



597
598
599
600

601
602
603
604
605
606

607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
...
656
657
658
659
660
661
662
663
664
665
666
667
668
669

670
671
672
673
674
675
676
677

678
679
680
681
682

683
684
685
686
687

688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705





706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
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
...
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
....
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
....
1061
1062
1063
1064
1065
1066
1067

1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
....
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
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
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
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
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
module Play.Qualifier exposing (..)

import Dict exposing (Dict)
import List.Extra as List
import Play.Data.Builtin as Builtin exposing (Builtin)
import Play.Data.Metadata as Metadata exposing (Metadata)
import Play.Data.SourceLocation as SourceLocation exposing (SourceLocationRange)
import Play.Data.Type as Type exposing (Type, WordType)
import Play.Data.TypeSignature as TypeSignature
import Play.Parser as Parser
import Play.Qualifier.Problem exposing (Problem(..))
................................................................................
import Result.Extra as Result
import Set exposing (Set)


type alias AST =
    { types : Dict String TypeDefinition
    , words : Dict String WordDefinition



    }


type





    TypeDefinition
    -- TODO: Each branch here should take a record. Too many arguments.
    = CustomTypeDef String Bool SourceLocationRange (List String) (List ( String, Type ))
    | UnionTypeDef String Bool SourceLocationRange (List String) (List Type)


type alias WordDefinition =
    { name : String
    , metadata : Metadata
    , implementation : WordImplementation
    }
................................................................................
    | Word SourceLocationRange String
    | WordRef SourceLocationRange String
    | ConstructType String
    | GetMember String String
    | SetMember String String
    | Builtin SourceLocationRange Builtin


type alias ModuleReferences =
    { aliases : Dict String String
    , imports : Dict String (List String)
    }


builtinDict : Dict String Builtin
builtinDict =
    Dict.fromList
        [ ( "+", Builtin.Plus )
        , ( "-", Builtin.Minus )
        , ( "*", Builtin.Multiply )
................................................................................


type alias RunConfig =
    { packageName : String
    , modulePath : String
    , ast : Parser.AST
    , externalModules : Dict String String
    , inProgressAST : AST
    }


run : RunConfig -> Result (List Problem) AST
run config =
    let
        ( typeErrors, qualifiedTypes ) =
            Dict.foldl (\_ val acc -> qualifyType config val acc) ( [], Dict.empty ) config.ast.types
                |> Tuple.mapSecond (\qt -> Dict.map (\_ v -> resolveUnionInTypeDefs qt v) qt)

        allQualifiedTypes =
            Dict.union qualifiedTypes config.inProgressAST.types

        ( wordErrors, qualifiedWords ) =
            Dict.foldl (\_ val acc -> qualifyDefinition config allQualifiedTypes val acc) ( [], Dict.empty ) config.ast.words







    in
    case ( typeErrors, wordErrors ) of
        ( [], [] ) ->
            Ok
                { types = qualifiedTypes
                , words = qualifiedWords



                }

        _ ->
            Err <| typeErrors ++ wordErrors


type alias ModuleDefinitionConfig a =
    { a
        | ast : Parser.AST
        , externalModules : Dict String String
    }


moduleDefinition : ModuleDefinitionConfig a -> Parser.ModuleDefinitionRec
moduleDefinition config =
    let
        defaultImports =
            if Dict.get "/core" config.externalModules == Just "play/standard_library" then
                Dict.fromList [ ( "/core", [] ) ]

            else
                Dict.empty
    in
    case config.ast.moduleDefinition of
        Parser.Undefined ->
            { imports = defaultImports
            , aliases = Dict.empty
            , exposes = Set.empty
            }

        Parser.Defined def ->
            { imports = Dict.union def.imports defaultImports
            , aliases = def.aliases
            , exposes = def.exposes
            }


resolveUnionInTypeDefs : Dict String TypeDefinition -> TypeDefinition -> TypeDefinition
resolveUnionInTypeDefs qt td =
    case td of
        CustomTypeDef exposed name range generics members ->
            CustomTypeDef exposed name range generics (List.map (Tuple.mapSecond (resolveUnion qt)) members)

        UnionTypeDef exposed name range generics memberTypes ->
            UnionTypeDef exposed name range generics (List.map (resolveUnion qt) memberTypes)


resolveUnion : Dict String TypeDefinition -> Type -> Type
resolveUnion typeDefs type_ =
    case type_ of
        Type.Custom typeName ->
            case Dict.get typeName typeDefs of
                Just (UnionTypeDef _ _ _ _ members) ->
                    Type.Union members

                _ ->
                    type_

        Type.CustomGeneric typeName types ->
            case Dict.get typeName typeDefs of
                Just (UnionTypeDef _ _ _ generics members) ->
                    let
                        genericsMap =
                            List.map2 Tuple.pair generics types
                                |> Dict.fromList

                        rebindGenerics t =
                            case t of
................................................................................

qualifyType :
    RunConfig
    -> Parser.TypeDefinition
    -> ( List Problem, Dict String TypeDefinition )
    -> ( List Problem, Dict String TypeDefinition )
qualifyType config typeDef ( errors, acc ) =
    let
        modDef =
            moduleDefinition config

        ( modRefs, exposes ) =
            ( { aliases = modDef.aliases
              , imports = modDef.imports
              }
            , modDef.exposes
            )
    in
    case typeDef of
        Parser.CustomTypeDef range name generics members ->
            let
                qualifiedName =
                    qualifyName config name

                qualifiedMemberResult =
                    List.map (Tuple.mapSecond (qualifyMemberType config modRefs range)) members
                        |> List.map raiseTupleError
                        |> Result.combine

                exposed =
                    Set.isEmpty exposes || Set.member name exposes

                raiseTupleError ( label, result ) =
                    case result of
                        Ok value ->
                            Ok ( label, value )

                        Err err ->
                            Err err
................................................................................
                Err err ->
                    ( err :: errors
                    , acc
                    )

                Ok qualifiedMembers ->
                    ( errors
                    , Dict.insert qualifiedName
                        (CustomTypeDef
                            qualifiedName
                            exposed
                            range
                            generics
                            qualifiedMembers
                        )
                        acc
                    )

        Parser.UnionTypeDef range name generics memberTypes ->
            let
                qualifiedName =
                    qualifyName config name

                exposed =
                    Set.isEmpty exposes || Set.member name exposes

                qualifiedMemberTypesResult =
                    List.map (qualifyMemberType config modRefs range) memberTypes
                        |> Result.combine
            in
            case qualifiedMemberTypesResult of
                Err err ->
                    ( err :: errors
                    , acc
                    )

                Ok qualifiedMemberTypes ->
                    ( errors
                    , Dict.insert qualifiedName
                        (UnionTypeDef
                            qualifiedName
                            exposed
                            range
                            generics
                            qualifiedMemberTypes
                        )
                        acc
                    )


qualifyMemberType :
    RunConfig
    -> ModuleReferences
    -> SourceLocationRange
    -> Parser.PossiblyQualifiedType
    -> Result Problem Type
qualifyMemberType config modRefs range type_ =
    let
        internalRefLookup path name binds =
            let
                qualifiedName =
                    path
                        ++ [ name ]
                        |> String.join "/"
                        |> qualifyPackageModule config.packageName

                bindResult =
                    binds
                        |> List.map (qualifyMemberType config modRefs range)
                        |> Result.combine
            in
            case ( Dict.get qualifiedName config.inProgressAST.types, bindResult ) of
                ( Just (CustomTypeDef _ False _ _ _), _ ) ->
                    Err <| TypeNotExposed range qualifiedName

                ( Just (CustomTypeDef _ True _ [] _), _ ) ->
                    Ok <| Type.Custom qualifiedName

                ( Just (CustomTypeDef _ True _ _ _), Ok qualifiedBinds ) ->
                    Ok <| Type.CustomGeneric qualifiedName qualifiedBinds

                ( Just (UnionTypeDef _ True _ _ memberTypes), _ ) ->
                    Ok <| Type.Union memberTypes

                ( Just (UnionTypeDef _ False _ _ _), _ ) ->
                    Err <| TypeNotExposed range qualifiedName

                _ ->
                    Err <| UnknownTypeRef range qualifiedName

        importsLookup name binds =
            case resolveImportedType config modRefs name of
                Just importedModule ->
                    if String.startsWith "/" importedModule then
                        let
                            nextPath =
                                importedModule
                                    |> String.dropLeft 1
                                    |> String.split "/"
                                    -- Drop author/packageName part
                                    |> List.drop 2
                        in
                        qualifyMemberType config modRefs range <|
                            Parser.ExternalRef nextPath name binds

                    else
                        qualifyMemberType config modRefs range <|
                            Parser.InternalRef (String.split "/" importedModule) name binds

                Nothing ->
                    Err <| UnknownTypeRef range name
    in
    case type_ of

        Parser.LocalRef "Int" [] ->
            Ok <| Type.Int

        Parser.LocalRef name [] ->
            case Dict.get name config.ast.types of
                Just _ ->
                    Ok <| Type.Custom (qualifyName config name)

                Nothing ->
                    importsLookup name []

        Parser.LocalRef name binds ->
            case Dict.get name config.ast.types of
                Just _ ->
                    let
                        bindResult =
                            binds
                                |> List.map (qualifyMemberType config modRefs range)
                                |> Result.combine
                    in
                    case bindResult of
                        Ok convertedBindings ->
                            Ok <|
                                Type.CustomGeneric
                                    (qualifyName config name)
                                    convertedBindings

                        Err err ->
                            Err err

                Nothing ->

                    importsLookup name binds

        Parser.InternalRef ([ possibleAlias ] as path) name binds ->
            case Dict.get possibleAlias modRefs.aliases of
                Just val ->
                    if String.startsWith "/" val then
                        let
                            newPath =
                                val
                                    |> String.split "/"
                                    |> List.drop 1
                        in
                        qualifyMemberType config modRefs range <|
                            Parser.ExternalRef newPath name binds

                    else
                        internalRefLookup (String.split "/" val) name binds

                Nothing ->
                    internalRefLookup path name binds

        Parser.InternalRef path name binds ->
            internalRefLookup path name binds

        Parser.ExternalRef path name binds ->
            let
                pathString =
                    "/" ++ String.join "/" path

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

                bindResult =
                    binds
                        |> List.map (qualifyMemberType config modRefs range)
                        |> Result.combine
            in
            case ( Dict.get qualifiedName config.inProgressAST.types, bindResult ) of
                ( Just (CustomTypeDef _ False _ _ _), _ ) ->
                    Err <| TypeNotExposed range qualifiedName

                ( Just (CustomTypeDef _ True _ [] _), _ ) ->
                    Ok <| Type.Custom qualifiedName

                ( Just (CustomTypeDef _ True _ _ _), Ok qualifiedBinds ) ->
                    Ok <| Type.CustomGeneric qualifiedName qualifiedBinds

                ( Just (UnionTypeDef _ True _ _ memberTypes), _ ) ->
                    Ok <| Type.Union memberTypes

                ( Just (UnionTypeDef _ False _ _ _), _ ) ->
                    Err <| TypeNotExposed range qualifiedName

                _ ->
                    Err <| UnknownTypeRef range qualifiedName

        Parser.Generic sym ->
            Ok (Type.Generic sym)

        Parser.StackRange sym ->
            Ok (Type.Generic sym)

        Parser.QuotationType sign ->
            let
                inputResult =
                    sign.input
                        |> List.map (qualifyMemberType config modRefs range)
                        |> Result.combine

                outputResult =
                    sign.output
                        |> List.map (qualifyMemberType config modRefs range)
                        |> Result.combine
            in
            case ( inputResult, outputResult ) of
                ( Ok input, Ok output ) ->
                    Ok <|
                        Type.Quotation
                            { input = input
                            , output = output
                            }

                ( Err input, _ ) ->
                    Err input

                ( _, Err output ) ->
                    Err output


qualifyDefinition :
    RunConfig
    -> Dict String TypeDefinition
    -> Parser.WordDefinition
    -> ( List Problem, Dict String WordDefinition )
    -> ( List Problem, Dict String WordDefinition )
qualifyDefinition config qualifiedTypes unqualifiedWord ( errors, acc ) =
    let
        ( whens, impl ) =
            case unqualifiedWord.implementation of
                Parser.SoloImpl defImpl ->
                    ( [], defImpl )

                Parser.MultiImpl whenImpl defImpl ->
                    ( whenImpl, defImpl )

        modDef =
            moduleDefinition config

        moduleReferences =
            { aliases = Dict.union unqualifiedWord.aliases modDef.aliases
            , imports = Dict.union unqualifiedWord.imports modDef.imports
            }

        ( newWordsAfterWhens, qualifiedWhensResult ) =


            whens
                |> List.foldr
                    (qualifyWhen
                        config
                        qualifiedTypes
                        unqualifiedWord.name
                        moduleReferences
                    )
                    ( acc, [] )
                |> Tuple.mapSecond Result.combine

        ( newWordsAfterImpl, qualifiedImplementationResult ) =

            initQualifyNode config unqualifiedWord.name moduleReferences newWordsAfterWhens impl

        qualifiedMetadataResult =
            qualifyMetadata config qualifiedTypes unqualifiedWord

        qualifiedName =
            qualifyName config unqualifiedWord.name
    in
    case ( qualifiedWhensResult, qualifiedImplementationResult, qualifiedMetadataResult ) of
        ( Ok qualifiedWhens, Ok qualifiedImplementation, Ok qualifiedMetadata ) ->
            ( errors



            , Dict.insert qualifiedName
                { name = qualifiedName
                , metadata = qualifiedMetadata
                , implementation =
                    if List.isEmpty qualifiedWhens then
                        SoloImpl qualifiedImplementation

................................................................................
                        MultiImpl qualifiedWhens qualifiedImplementation
                }
                newWordsAfterImpl
            )

        ( Err whenError, _, _ ) ->
            ( whenError :: errors

            , newWordsAfterImpl
            )

        ( _, Err implError, _ ) ->
            ( implError :: errors

            , newWordsAfterImpl
            )

        ( _, _, Err metaError ) ->
            ( metaError :: errors

            , newWordsAfterImpl
            )


qualifyMetadata :
    RunConfig
    -> Dict String TypeDefinition
    -> Parser.WordDefinition
    -> Result Problem Metadata
qualifyMetadata config qualifiedTypes word =
    let
        wordRange =
            Maybe.withDefault SourceLocation.emptyRange word.sourceLocationRange

        inputLength =
            case word.typeSignature of
                Parser.NotProvided ->
                    0

                Parser.UserProvided wt ->
                    List.length wt.input

                Parser.Verified wt ->
                    List.length wt.input

        modDef =
            moduleDefinition config

        modRefs =
            { aliases = Dict.union modDef.aliases word.aliases
            , imports = Dict.union modDef.imports word.imports
            }
    in

    Parser.typeSignatureToMaybe word.typeSignature
        |> Maybe.map (\ts -> ts.input ++ ts.output)
        |> Maybe.withDefault []

        |> List.map (qualifyMemberType config modRefs wordRange)
        |> Result.combine
        |> Result.map
            (\qualifiedFlatTypeSignature ->
                let
                    wordType =
                        { input = List.take inputLength qualifiedFlatTypeSignature
                        , output = List.drop inputLength qualifiedFlatTypeSignature
                        }

                    ts =
                        case word.typeSignature of
                            Parser.NotProvided ->
                                TypeSignature.NotProvided




                            Parser.UserProvided _ ->
                                TypeSignature.UserProvided wordType


                            Parser.Verified _ ->
                                TypeSignature.CompilerProvided wordType

                    baseMeta =
                        Metadata.default
                in

                { baseMeta
                    | type_ =
                        TypeSignature.map (resolveUnions qualifiedTypes) ts
                    , isExposed =
                        case config.ast.moduleDefinition of
                            Parser.Undefined ->
                                True

                            Parser.Defined def ->
                                Set.member word.name def.exposes
                }
            )


validateTypeReferences : RunConfig -> Dict String TypeDefinition -> SourceLocationRange -> Type -> Result Problem Type
validateTypeReferences config typeDefs wordRange type_ =
    case type_ of
................................................................................
    }


qualifyWhen :
    RunConfig
    -> Dict String TypeDefinition
    -> String
    -> ModuleReferences
    -> ( Parser.TypeMatch, List Parser.AstNode )
    -> ( Dict String WordDefinition, List (Result Problem ( TypeMatch, List Node )) )
    -> ( Dict String WordDefinition, List (Result Problem ( TypeMatch, List Node )) )
qualifyWhen config qualifiedTypes wordName modRefs ( typeMatch, impl ) ( qualifiedWords, result ) =
    let
        ( newWords, qualifiedImplementationResult ) =

            initQualifyNode config wordName modRefs qualifiedWords impl

        qualifiedMatchResult =
            qualifyMatch config qualifiedTypes modRefs typeMatch
    in
    case ( qualifiedImplementationResult, qualifiedMatchResult ) of
        ( Err err, _ ) ->
            ( newWords

            , Err err :: result
            )

        ( _, Err err ) ->
            ( newWords

            , Err err :: result
            )

        ( Ok qualifiedImplementation, Ok qualifiedMatch ) ->
            ( newWords

            , Ok ( qualifiedMatch, qualifiedImplementation ) :: result
            )


qualifyMatch :
    RunConfig
    -> Dict String TypeDefinition
    -> ModuleReferences
    -> Parser.TypeMatch
    -> Result Problem TypeMatch
qualifyMatch config qualifiedTypes modRefs typeMatch =
    let
        qualifiedNameToMatch range name patterns =
            case Dict.get name qualifiedTypes of
                Just (CustomTypeDef _ False _ _ _) ->
                    Err <| TypeNotExposed range name

                Just (CustomTypeDef _ True _ gens members) ->





                    let
                        memberNames =
                            members
                                |> List.map Tuple.first
                                |> Set.fromList

                        qualifiedPatternsResult =
                            patterns
                                |> List.map
                                    (qualifyMatchValue
                                        config
                                        qualifiedTypes
                                        modRefs
                                        range
                                        name
                                        memberNames
                                    )
                                |> Result.combine

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

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

                        Err err ->
                            Err err

                Just (UnionTypeDef _ False _ _ _) ->
                    Err <| TypeNotExposed range name

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

                    else
                        Err <| UnionTypeMatchWithPatterns range

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

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

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

        Parser.TypeMatch range (Parser.LocalRef name []) patterns ->
            case qualifiedNameToMatch range (qualifyName config name) patterns of
                (Err (UnknownTypeRef _ _)) as errMsg ->
                    case resolveImportedType config modRefs name of
                        Just importedModule ->
                            qualifiedNameToMatch 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 String.startsWith "/" actualPath then
                        let
                            extPath =
                                actualPath
                                    |> String.dropLeft 1
                                    |> String.split "/"
                        in
                        qualifyMatch config qualifiedTypes modRefs <|
                            Parser.TypeMatch range (Parser.ExternalRef extPath name []) patterns

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

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

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

        Parser.TypeMatch range _ _ ->
            Err <| InvalidTypeMatch range


qualifyMatchValue :
    RunConfig
    -> Dict String TypeDefinition
    -> ModuleReferences
    -> SourceLocationRange
    -> String
    -> Set String
    -> ( String, Parser.TypeMatchValue )
    -> Result Problem ( String, TypeMatchValue )
qualifyMatchValue config qualifiedTypes modRefs range typeName memberNames ( fieldName, matchValue ) =
    if Set.member fieldName memberNames then
        case matchValue of
            Parser.LiteralInt val ->
                Ok <| ( fieldName, LiteralInt val )

            Parser.LiteralType type_ ->
                let
                    qualifyTypeResult =
                        qualifyMemberType config modRefs range type_
                in
                case qualifyTypeResult of
                    Ok qualifiedType ->
                        Ok <| ( fieldName, LiteralType qualifiedType )

                    Err err ->
                        Err err

            Parser.RecursiveMatch typeMatch ->
                case qualifyMatch config qualifiedTypes modRefs typeMatch of
                    Err err ->
                        Err err

                    Ok match ->
                        Ok <| ( fieldName, RecursiveMatch match )

    else
        Err <| NoSuchMemberOnType range typeName fieldName


initQualifyNode :

    RunConfig
    -> String
    -> ModuleReferences
    -> Dict String WordDefinition
    -> List Parser.AstNode
    -> ( Dict String WordDefinition, Result Problem (List Node) )

initQualifyNode config currentDefName modRefs qualifiedWords impl =
    List.foldr
        (qualifyNode config currentDefName modRefs)
        (initQualifyNodeAccumulator qualifiedWords)
        impl
        |> (\acc -> ( acc.qualifiedWords, Result.combine acc.qualifiedNodes ))


type alias QualifyNodeAccumulator =
    { availableQuoteId : Int
    , qualifiedWords : Dict String WordDefinition
    , qualifiedNodes : List (Result Problem Node)

    }


initQualifyNodeAccumulator : Dict String WordDefinition -> QualifyNodeAccumulator
initQualifyNodeAccumulator qualifiedWords =
    { availableQuoteId = 1
    , qualifiedWords = qualifiedWords
    , qualifiedNodes = []

    }


qualifyNode :
    RunConfig
    -> String
    -> ModuleReferences
    -> Parser.AstNode
    -> QualifyNodeAccumulator
    -> QualifyNodeAccumulator
qualifyNode config currentDefName modRefs node acc =
    case node of
        Parser.Integer loc value ->
            { acc | qualifiedNodes = Ok (Integer loc value) :: acc.qualifiedNodes }

        Parser.Word loc value ->
            let
                qualifiedName =
................................................................................

            else
                case Dict.get value builtinDict of
                    Just builtin ->
                        { acc | qualifiedNodes = Ok (Builtin loc builtin) :: acc.qualifiedNodes }

                    Nothing ->
                        case resolveImportedWord config modRefs value of
                            Nothing ->
                                { acc | qualifiedNodes = Err (UnknownWordRef loc value) :: acc.qualifiedNodes }

                            Just mod ->
                                if String.startsWith "/" mod then
                                    let
                                        path =
                                            mod
                                                |> String.split "/"
                                                |> List.drop 3
                                    in
                                    qualifyNode
                                        config
                                        currentDefName
                                        modRefs
                                        (Parser.ExternalWord loc path value)
                                        acc

                                else
                                    let
                                        path =
                                            String.split "/" mod
                                    in
                                    qualifyNode
                                        config
                                        currentDefName
                                        modRefs
                                        (Parser.PackageWord loc path value)
                                        acc

        Parser.PackageWord loc path value ->
            let
                normalizedPathPreAliasCheck =
                    String.join "/" path

                normalizedPath =
                    Dict.get normalizedPathPreAliasCheck modRefs.aliases
                        |> Maybe.withDefault normalizedPathPreAliasCheck
            in
            if String.startsWith "/" normalizedPath then
                let
                    externalWordNode =
                        Parser.ExternalWord
                            loc
                            (List.drop 1 <| String.split "/" normalizedPath)
                            value
                in
                qualifyNode config currentDefName modRefs externalWordNode acc

            else
                let
                    qualifiedPath =
                        qualifyPackageModule config.packageName normalizedPath

                    qualifiedName =
                        String.join "/" [ qualifiedPath, value ]

                    _ =
                        Dict.keys config.inProgressAST.words
                in

                case Dict.get qualifiedName config.inProgressAST.words of
                    Nothing ->
                        { acc | qualifiedNodes = Err (UnknownWordRef loc qualifiedName) :: acc.qualifiedNodes }

                    Just word ->
                        if word.metadata.isExposed then
                            { acc | qualifiedNodes = Ok (Word loc qualifiedName) :: acc.qualifiedNodes }


                        else
                            { acc | qualifiedNodes = Err (WordNotExposed loc qualifiedName) :: acc.qualifiedNodes }

        Parser.ExternalWord loc path value ->
            let
                normalizedPath =
                    "/" ++ String.join "/" path
            in
            case Dict.get normalizedPath config.externalModules of
                Nothing ->
                    { acc | qualifiedNodes = Err (UnknownWordRef loc (normalizedPath ++ "/" ++ value)) :: acc.qualifiedNodes }

                Just package ->
                    let
                        fullReference =
                            String.concat
                                [ "/"
                                , package
                                , normalizedPath
                                , "/"
                                , value
                                ]


                    in

                    case Dict.get fullReference config.inProgressAST.words of
                        Nothing ->
                            { acc | qualifiedNodes = Err (UnknownWordRef loc fullReference) :: acc.qualifiedNodes }

                        Just def ->
                            if def.metadata.isExposed then
                                { acc | qualifiedNodes = Ok (Word loc fullReference) :: acc.qualifiedNodes }


                            else
                                { acc | qualifiedNodes = Err (WordNotExposed loc fullReference) :: acc.qualifiedNodes }

        Parser.ConstructType typeName ->
            { acc | qualifiedNodes = Ok (ConstructType (qualifyName config typeName)) :: acc.qualifiedNodes }

        Parser.SetMember typeName memberName ->
            { acc | qualifiedNodes = Ok (SetMember (qualifyName config typeName) memberName) :: acc.qualifiedNodes }

................................................................................
                quoteName =
                    if String.startsWith "quote:" currentDefName then
                        currentDefName ++ "/" ++ String.fromInt acc.availableQuoteId

                    else
                        "quote:" ++ qualifyName config currentDefName ++ "/" ++ String.fromInt acc.availableQuoteId

                ( newWordsAfterQuot, qualifiedQuotImplResult ) =
                    initQualifyNode config quoteName modRefs acc.qualifiedWords quotImpl
            in
            case qualifiedQuotImplResult of
                Ok qualifiedQuotImpl ->
                    { acc
                        | availableQuoteId = acc.availableQuoteId + 1
                        , qualifiedWords =
                            Dict.insert quoteName
................................................................................
                                , metadata =
                                    Metadata.default
                                        |> Metadata.isQuoted
                                , implementation = SoloImpl qualifiedQuotImpl
                                }
                                newWordsAfterQuot
                        , qualifiedNodes = Ok (WordRef sourceLocation quoteName) :: acc.qualifiedNodes

                    }

                Err err ->
                    { acc | qualifiedNodes = Err err :: acc.qualifiedNodes }


typeDefinitionName : TypeDefinition -> String
typeDefinitionName typeDef =
    case typeDef of
        CustomTypeDef name _ _ _ _ ->
            name

        UnionTypeDef name _ _ _ _ ->
            name


qualifyName : RunConfig -> String -> String
qualifyName config name =
    if config.packageName == "" then
        name
................................................................................
            , "/"
            , config.modulePath
            , "/"
            , name
            ]


qualifyPackageModule : String -> String -> String
qualifyPackageModule packageName path =
    if packageName == "" then
        path

    else
        String.concat
            [ "/"
            , packageName
            , "/"
            , path
            ]


resolveImportedWord : RunConfig -> ModuleReferences -> String -> Maybe String
resolveImportedWord config modRefs name =
    let
        explicitImports =
            modRefs.imports
                |> Dict.toList
                |> List.find (\( _, v ) -> List.member name v)
                |> Maybe.map Tuple.first
                |> Maybe.andThen resolveMod

        potentialCandidates =
            modRefs.imports
                |> Dict.filter (\_ v -> List.isEmpty v)
                |> Dict.keys
                |> List.filterMap resolveMod
                |> List.map (\mod -> ( mod, mod ++ "/" ++ name ))

        resolveMod mod =
            if String.startsWith "/" mod then
                Dict.get mod config.externalModules
                    |> Maybe.map
                        (\package ->
                            qualifyPackageModule package (String.dropLeft 1 mod)
                        )

            else
                Just <| qualifyPackageModule config.packageName mod
    in
    case explicitImports of
        Just _ ->
            explicitImports

        Nothing ->
            potentialCandidates
                |> List.map (\( mod, qName ) -> ( mod, Dict.get qName config.inProgressAST.words ))
                |> List.filter (\( _, possibleDef ) -> possibleDef /= Nothing)
                |> List.head
                |> Maybe.map Tuple.first


resolveImportedType : RunConfig -> ModuleReferences -> String -> Maybe String
resolveImportedType config modRefs name =
    let
        explicitImports =
            modRefs.imports
                |> Dict.toList
                |> List.find (\( _, v ) -> List.member name v)
                |> Maybe.map Tuple.first
                |> Maybe.andThen resolveMod

        potentialCandidates =
            modRefs.imports
                |> Dict.filter (\_ v -> List.isEmpty v)
                |> Dict.keys
                |> List.filterMap resolveMod
                |> List.map (\mod -> ( mod, mod ++ "/" ++ name ))

        resolveMod mod =
            if String.startsWith "/" mod then
                Dict.get mod config.externalModules
                    |> Maybe.map
                        (\package ->
                            String.dropLeft 1 mod
                                |> qualifyPackageModule package
                        )

            else
                Just <| qualifyPackageModule config.packageName mod
    in
    case explicitImports of
        Just _ ->
            explicitImports

        Nothing ->
            potentialCandidates
                |> List.map (\( mod, qName ) -> ( mod, Dict.get qName config.inProgressAST.types ))
                |> List.filter (\( _, possibleDef ) -> possibleDef /= Nothing)
                |> List.head
                |> Maybe.map Tuple.first



-- Dependant modules


type alias RequiredModulesConfig =
    { packageName : String
    , ast : Parser.AST
    , externalModules : Dict String String
    }


requiredModules : RequiredModulesConfig -> Set String
requiredModules config =
    let
        modDef =
            moduleDefinition config

        topLevelAliases =
            modDef.aliases

        topLevelAliasTargets =
            topLevelAliases
                |> Dict.values
                |> Set.fromList

        topLevelImports =
            modDef.imports
                |> Dict.keys
                |> Set.fromList

        typeRequirements =
            config.ast.types
                |> Dict.foldl
                    (\_ t acc -> Set.union (requiredModulesOfType t) acc)
                    Set.empty

        wordRequirements =
            config.ast.words
                |> Dict.foldl
                    (\_ w acc -> Set.union (requiredModulesOfWord topLevelAliases w) acc)
                    Set.empty

        fullyQualify mod acc =
            if String.startsWith "/" mod then
                case Dict.get mod config.externalModules of
                    Just package ->
                        Set.insert
                            (String.concat
                                [ "/"
                                , package
                                , mod
                                ]
                            )
                            acc

                    Nothing ->
                        acc

            else
                Set.insert (qualifyPackageModule config.packageName mod) acc
    in
    topLevelAliasTargets
        |> Set.union topLevelImports
        |> Set.union typeRequirements
        |> Set.union wordRequirements
        |> Set.foldl fullyQualify Set.empty


requiredModulesOfType : Parser.TypeDefinition -> Set String
requiredModulesOfType typeDef =
    case typeDef of
        Parser.CustomTypeDef _ _ _ members ->
            members
                |> List.map Tuple.second
                |> List.filterMap extractModuleReferenceFromType
                |> Set.fromList

        Parser.UnionTypeDef _ _ _ members ->
            members
                |> List.filterMap extractModuleReferenceFromType
                |> Set.fromList


requiredModulesOfWord : Dict String String -> Parser.WordDefinition -> Set String
requiredModulesOfWord topLevelAliases word =
    let
        wordAliases =
            word.aliases
                |> Dict.values
                |> Set.fromList

        wordImports =
            word.imports
                |> Dict.keys
                |> Set.fromList

        typeSignature =
            case word.typeSignature of
                Parser.NotProvided ->
                    Set.empty

                Parser.UserProvided wordType ->
                    moduleReferenceFromWordType wordType

                Parser.Verified wordType ->
                    moduleReferenceFromWordType wordType

        moduleReferenceFromWordType wordType =
            wordType.input
                ++ wordType.output
                |> List.filterMap extractModuleReferenceFromType
                |> Set.fromList

        matches =
            case word.implementation of
                Parser.SoloImpl _ ->
                    Set.empty

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

        extractMatchType (Parser.TypeMatch _ tipe _) =
            tipe

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

                Parser.MultiImpl branches impl ->
                    impl :: List.map Tuple.second branches

        wordReferences =
            impls
                |> List.concat
                |> List.filterMap (extractModuleReferenceFromNode topLevelAliases word)
                |> Set.fromList
    in
    wordAliases
        |> Set.union wordImports
        |> Set.union typeSignature
        |> Set.union matches
        |> Set.union wordReferences


extractModuleReferenceFromType : Parser.PossiblyQualifiedType -> Maybe String
extractModuleReferenceFromType ref =
    case ref of
        Parser.ExternalRef path _ _ ->
            Just <| "/" ++ String.join "/" path

        Parser.InternalRef path _ _ ->
            Just <| String.join "/" path

        _ ->
            Nothing


extractModuleReferenceFromNode : Dict String String -> Parser.WordDefinition -> Parser.AstNode -> Maybe String
extractModuleReferenceFromNode topLevelAliases meta node =
    case node of
        Parser.PackageWord _ [ potentialAlias ] _ ->
            case
                ( Dict.get potentialAlias topLevelAliases
                , Dict.get potentialAlias meta.aliases
                )
            of
                ( Just _, _ ) ->
                    Nothing

                ( _, Just _ ) ->
                    Nothing

                ( Nothing, Nothing ) ->
                    Just potentialAlias

        Parser.PackageWord _ path _ ->
            Just (String.join "/" path)

        Parser.ExternalWord _ path _ ->
            Just ("/" ++ String.join "/" path)

        _ ->
            Nothing

Modified src/Play/Qualifier/Problem.elm from [9fd0a6e7f6] to [cf36a1d3b1].

8
9
10
11
12
13
14


15
16
17
18
19
20
21
..
44
45
46
47
48
49
50















type Problem
    = UnknownWordRef SourceLocationRange String
    | UnknownTypeRef SourceLocationRange String
    | UnionTypeMatchWithPatterns SourceLocationRange
    | InvalidTypeMatch SourceLocationRange
    | NoSuchMemberOnType SourceLocationRange String String




toString : String -> Problem -> String
toString source problem =
    case problem of
        UnknownWordRef range wordRef ->
            SourceLocation.extractFromString source range
................................................................................
        NoSuchMemberOnType range typeName member ->
            SourceLocation.extractFromString source range
                ++ "\n\n"
                ++ typeName
                ++ " does not have a member called '"
                ++ member
                ++ "'."





















>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
..
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

type Problem
    = UnknownWordRef SourceLocationRange String
    | UnknownTypeRef SourceLocationRange String
    | UnionTypeMatchWithPatterns SourceLocationRange
    | InvalidTypeMatch SourceLocationRange
    | NoSuchMemberOnType SourceLocationRange String String
    | WordNotExposed SourceLocationRange String
    | TypeNotExposed SourceLocationRange String


toString : String -> Problem -> String
toString source problem =
    case problem of
        UnknownWordRef range wordRef ->
            SourceLocation.extractFromString source range
................................................................................
        NoSuchMemberOnType range typeName member ->
            SourceLocation.extractFromString source range
                ++ "\n\n"
                ++ typeName
                ++ " does not have a member called '"
                ++ member
                ++ "'."

        WordNotExposed range wordRef ->
            SourceLocation.extractFromString source range
                ++ "\n\n"
                ++ "Trying to call '"
                ++ wordRef
                ++ "' but this function is not exposed."

        TypeNotExposed range typeRef ->
            SourceLocation.extractFromString source range
                ++ "\n\n"
                ++ "Referencing '"
                ++ typeRef
                ++ "' but this type is not exposed."

Modified src/Play/TypeChecker.elm from [03b15c559b] to [267b56b8c9].

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
initContext : LoadedQualifierAST a -> Context
initContext ast =
    let
        concreteTypes =
            Dict.map
                (\_ t ->
                    case t of
                        Qualifier.CustomTypeDef name range generics members ->
                            CustomTypeDef name range generics members

                        Qualifier.UnionTypeDef name range generics memberTypes ->
                            UnionTypeDef name range generics memberTypes
                )
                ast.types

        genericErrors t =
            let
                collectReferencedGenerics memberTypes =







|


|







84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
initContext : LoadedQualifierAST a -> Context
initContext ast =
    let
        concreteTypes =
            Dict.map
                (\_ t ->
                    case t of
                        Qualifier.CustomTypeDef name _ range generics members ->
                            CustomTypeDef name range generics members

                        Qualifier.UnionTypeDef name _ range generics memberTypes ->
                            UnionTypeDef name range generics memberTypes
                )
                ast.types

        genericErrors t =
            let
                collectReferencedGenerics memberTypes =

Modified src/TestCompiler.elm from [3aebcaa4ec] to [3223a451b4].

1
2
3
4
5

6
7
8
9
10
11
12
..
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
..
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
..
91
92
93
94
95
96
97
98
99
100
101
port module Main exposing (main)

import Dict
import Platform exposing (Program)
import Play.Codegen as Codegen

import Play.Parser as Parser
import Play.Parser.Problem as ParserProblem
import Play.Qualifier as Qualifier
import Play.Qualifier.Problem as QualifierProblem
import Play.TypeChecker as TypeChecker
import Play.TypeChecker.Problem as TypeCheckerProblem
import Wasm
................................................................................


type alias Model =
    ()


type Msg
    = CompileString String


main : Program () Model Msg
main =
    Platform.worker
        { init = init
        , update = update
................................................................................
    , Cmd.none
    )


update : Msg -> Model -> ( Model, Cmd Msg )
update msg _ =
    case msg of
        CompileString sourceCode ->
            case compile sourceCode of
                Ok wasm ->
                    ( ()
                    , compileFinished ( True, Wasm.toString wasm )
                    )

                Err errmsg ->
                    ( ()
                    , compileFinished ( False, "Compilation failed:\n\n" ++ errmsg )
                    )


compile : String -> Result String Wasm.Module
compile sourceCode =
    case Parser.run sourceCode of
        Err parserErrors ->
            formatErrors (ParserProblem.toString sourceCode) parserErrors

        Ok ast ->
            let
                qualifierResult =
                    Qualifier.run
                        { packageName = ""
                        , modulePath = ""
                        , ast = ast
                        , externalModules = Dict.empty



                        }





            in
            case qualifierResult of
                Err qualifierErrors ->
                    formatErrors (QualifierProblem.toString sourceCode) qualifierErrors

                Ok qualifiedAst ->
                    case TypeChecker.run qualifiedAst of
................................................................................


subscriptions : Model -> Sub Msg
subscriptions _ =
    compileString CompileString


port compileString : (String -> msg) -> Sub msg


port compileFinished : ( Bool, String ) -> Cmd msg
|




>







 







|







 







|
|











|
|












>
>
>
|
>
>
>
>
>







 







|



1
2
3
4
5
6
7
8
9
10
11
12
13
..
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
..
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
...
100
101
102
103
104
105
106
107
108
109
110
port module TestCompiler exposing (main)

import Dict
import Platform exposing (Program)
import Play.Codegen as Codegen
import Play.Data.Metadata as Metadata
import Play.Parser as Parser
import Play.Parser.Problem as ParserProblem
import Play.Qualifier as Qualifier
import Play.Qualifier.Problem as QualifierProblem
import Play.TypeChecker as TypeChecker
import Play.TypeChecker.Problem as TypeCheckerProblem
import Wasm
................................................................................


type alias Model =
    ()


type Msg
    = CompileString ( String, String )


main : Program () Model Msg
main =
    Platform.worker
        { init = init
        , update = update
................................................................................
    , Cmd.none
    )


update : Msg -> Model -> ( Model, Cmd Msg )
update msg _ =
    case msg of
        CompileString ( entry, sourceCode ) ->
            case compile entry sourceCode of
                Ok wasm ->
                    ( ()
                    , compileFinished ( True, Wasm.toString wasm )
                    )

                Err errmsg ->
                    ( ()
                    , compileFinished ( False, "Compilation failed:\n\n" ++ errmsg )
                    )


compile : String -> String -> Result String Wasm.Module
compile entry sourceCode =
    case Parser.run sourceCode of
        Err parserErrors ->
            formatErrors (ParserProblem.toString sourceCode) parserErrors

        Ok ast ->
            let
                qualifierResult =
                    Qualifier.run
                        { packageName = ""
                        , modulePath = ""
                        , ast = ast
                        , externalModules = Dict.empty
                        , inProgressAST =
                            { types = Dict.empty
                            , words = Dict.empty
                            }
                        }
                        |> Result.map (\qast -> { qast | words = Dict.update entry (Maybe.map setEntryPoint) qast.words })

                setEntryPoint word =
                    { word | metadata = Metadata.asEntryPoint word.metadata }
            in
            case qualifierResult of
                Err qualifierErrors ->
                    formatErrors (QualifierProblem.toString sourceCode) qualifierErrors

                Ok qualifiedAst ->
                    case TypeChecker.run qualifiedAst of
................................................................................


subscriptions : Model -> Sub Msg
subscriptions _ =
    compileString CompileString


port compileString : (( String, String ) -> msg) -> Sub msg


port compileFinished : ( Bool, String ) -> Cmd msg

Modified src/Wasm.elm from [0c6d3e3be9] to [287b980b46].

302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

            else
                "(local " ++ (String.join " " <| List.map typeToString function.locals) ++ ")"

        fullFuncDef =
            String.join " "
                [ "(func"
                , "$" ++ function.name
                , "(type " ++ String.fromInt function.typeSignatureIndex ++ ")"
                , locals
                ]
    in
    [ Str fullFuncDef
    , Indent <| List.map (formatInstruction module_) function.instructions
    , Str ")"







|







302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

            else
                "(local " ++ (String.join " " <| List.map typeToString function.locals) ++ ")"

        fullFuncDef =
            String.join " "
                [ "(func"
                , "$" ++ String.replace "," "__COMMA__" function.name
                , "(type " ++ String.fromInt function.typeSignatureIndex ++ ")"
                , locals
                ]
    in
    [ Str fullFuncDef
    , Indent <| List.map (formatInstruction module_) function.instructions
    , Str ")"

Modified stdlib/src/core.play from [b4257695bb] to [f0362b91dc].




















1
2
3
4
5
6
7



















# Everything in core is imported into every module outside the standard library

# booleans

defunion: Bool
: True
: False
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
defmodule:
exposing:
  Bool
  True
  False
  not
  select
  if
  over
  drop2
  split
  zero?
  int=
  negate
  square
  inc
  dec
:

# Everything in core is imported into every module outside the standard library

# booleans

defunion: Bool
: True
: False

Modified stdlib/src/list.play from [a7b678c1a9] to [ac6dd828cb].



















1
2
3
4
5
6
7
..
16
17
18
19
20
21
22




23
24
25
26
27
28
29
..
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49


















defunion: List a
: NonEmpty a
: Empty

defstruct: NonEmpty a
: first a
: rest (List a)
................................................................................
type: a a -- (NonEmpty a)
: Empty >NonEmpty >NonEmpty

def: of-three
type: a a a -- (NonEmpty a)
: Empty >NonEmpty >NonEmpty >NonEmpty





defmulti: fold
type: (List a) b [ a b -- b ] -- b
: Empty
  drop swap drop
: NonEmpty
  pair/>Pair
  swap # (Pair b quot) (NonEmpty a)
................................................................................
  swap pair/second> # rest b quot
  fold

def: reverse
type: (List a) -- (List a)
: Empty [ >NonEmpty ] fold

def: fold-right
type: (List a) b [ a b -- b ] -- b
: -rotate reverse rotate fold

def: test
: 1 2 3 of-three
  0 [ + ] fold

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







 







>
>
>
>







 







|


<
<
<
<
<
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
..
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
57
58
59
60
61
62
63
64
65
66





defmodule:
exposing:
  List
  NonEmpty
  >first
  first>
  >rest
  rest>
  Empty
  of-one
  of-two
  of-three
  ,
  fold
  reverse
  fold-reverse
:

defunion: List a
: NonEmpty a
: Empty

defstruct: NonEmpty a
: first a
: rest (List a)
................................................................................
type: a a -- (NonEmpty a)
: Empty >NonEmpty >NonEmpty

def: of-three
type: a a a -- (NonEmpty a)
: Empty >NonEmpty >NonEmpty >NonEmpty

def: ,
type: (List a) a -- (NonEmpty a)
: swap >NonEmpty

defmulti: fold
type: (List a) b [ a b -- b ] -- b
: Empty
  drop swap drop
: NonEmpty
  pair/>Pair
  swap # (Pair b quot) (NonEmpty a)
................................................................................
  swap pair/second> # rest b quot
  fold

def: reverse
type: (List a) -- (List a)
: Empty [ >NonEmpty ] fold

def: fold-reverse
type: (List a) b [ a b -- b ] -- b
: -rotate reverse rotate fold





Modified stdlib/src/maybe.play from [00d98b8fe3] to [081e92a1e7].









1
2
3
4
5
6
7








defunion: Maybe a
: a
: Nothing

defstruct: Nothing

defmulti: map
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
defmodule:
exposing:
  Maybe
  Nothing
  map
  when-nothing
:

defunion: Maybe a
: a
: Nothing

defstruct: Nothing

defmulti: map

Modified stdlib/src/pair.play from [0056df763e] to [6c626d6606].















1
2
3
4
5
6
7














defstruct: Pair a b
: first a
: second b

def: spill
type: (Pair a b) -- a b
: [ first> ] [ second> ] core/split
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
defmodule:
exposing:
  Pair
  >Pair
  >first
  first>
  >second
  second>
  spill
  map
  map-first
  map-second
:

defstruct: Pair a b
: first a
: second b

def: spill
type: (Pair a b) -- a b
: [ first> ] [ second> ] core/split

Modified tests/Test/PackageLoader.elm from [da9199a4ec] to [670203e2f4].

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
..
75
76
77
78
79
80
81












































82
83
84
85
86
87
88
...
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
...
228
229
230
231
232
233
234




























235
236
237
238
239
240
241
...
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
...
349
350
351
352
353
354
355










































                        , PackageLoader.ReadFile "/project/lib/version" "play.json"
                        , PackageLoader.ResolvePackageModules "robheghan/fnv" "/project"
                        , PackageLoader.ResolvePackageModules "jarvis/template_strings" "/project/lib/template_strings"
                        , PackageLoader.ResolvePackageModules "play/version" "/project/lib/template_strings/lib/version"
                        , PackageLoader.ReadFile "/project/src" "mod1.play"
                        , PackageLoader.ReadFile "/project/lib/template_strings/lib/version/src/version" "data.play"
                        ]
        , test "Compiles to qualified AST" <|
            \_ ->
                let
                    loaderResult =
                        PackageLoader.init initOpts
                            |> resolveSideEffects testFiles []
                            |> Result.map Tuple.second
                in
................................................................................
                                      , metadata = Metadata.default
                                      , implementation =
                                            Qualifier.SoloImpl
                                                [ Qualifier.Integer emptyRange 2
                                                ]
                                      }
                                    ]












































                            }
                            (Util.stripLocations ast)
        , test "Specified entry point is marked as such" <|
            \_ ->
                let
                    loaderResult =
                        PackageLoader.init
................................................................................
            Expect.equalLists [] (sfDiff ++ sfDiffRev)


resolveSideEffects :
    Dict String String
    -> List PackageLoader.SideEffect
    -> PackageLoader.Model
    -> Result String ( List PackageLoader.SideEffect, Qualifier.ExposedAST )
resolveSideEffects fileSystem seenSfs model =
    case PackageLoader.getSideEffect model of
        Nothing ->
            case model of
                PackageLoader.Done ast ->
                    Ok ( seenSfs, ast )

................................................................................
        case pathParts of
            [ _, "play.json" ] ->
                True

            _ ->
                False






























testFiles : Dict String String
testFiles =
    Dict.fromList
        [ ( "/project/play.json"
          , """
            {
................................................................................
          )
        , ( "/project/lib/template_strings/src/template_strings/mod.play"
          , """
            def: dec
            : 1 =
            """
          )
        , ( "/project/lib/unused/play.json"
          , """
            {
                "name": "some/useless",
                "version": "1.7.0",
                "language-version": "0.2.0",
                "exposed-modules": [
                    "useless/mod"
                ],
                "dependencies": {
                },
                "package-paths": [
                ]
            }
          """
          )
        , ( "/project/lib/unused/src/useless/mod.play"
          , """
            def: square
            : dup *
            """
          )
        , ( "/project/lib/version/play.json"
          , """
            {
                "name": "play/version",
                "version": "1.0.0",
                "language-version": "0.2.0",
                "exposed-modules": [
................................................................................
        , ( "/project/lib/template_strings/lib/version/src/version/data.play"
          , """
            def: number
            : 2
            """
          )
        ]

















































|







 







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







 







|







 







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







 







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







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
..
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
...
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
...
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
...
354
355
356
357
358
359
360






















361
362
363
364
365
366
367
...
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
                        , PackageLoader.ReadFile "/project/lib/version" "play.json"
                        , PackageLoader.ResolvePackageModules "robheghan/fnv" "/project"
                        , PackageLoader.ResolvePackageModules "jarvis/template_strings" "/project/lib/template_strings"
                        , PackageLoader.ResolvePackageModules "play/version" "/project/lib/template_strings/lib/version"
                        , PackageLoader.ReadFile "/project/src" "mod1.play"
                        , PackageLoader.ReadFile "/project/lib/template_strings/lib/version/src/version" "data.play"
                        ]
        , test "Compiles project with external dependencies to qualified AST" <|
            \_ ->
                let
                    loaderResult =
                        PackageLoader.init initOpts
                            |> resolveSideEffects testFiles []
                            |> Result.map Tuple.second
                in
................................................................................
                                      , metadata = Metadata.default
                                      , implementation =
                                            Qualifier.SoloImpl
                                                [ Qualifier.Integer emptyRange 2
                                                ]
                                      }
                                    ]
                            }
                            (Util.stripLocations ast)
        , test "Compiles project with multiple dependant modules to qualified AST" <|
            \_ ->
                let
                    loaderResult =
                        PackageLoader.init initOpts
                            |> resolveSideEffects testFilesInternalConsistency []
                            |> Result.map Tuple.second
                in
                case loaderResult of
                    Err msg ->
                        Expect.fail msg

                    Ok ast ->
                        Expect.equal
                            { types =
                                Dict.fromListBy Qualifier.typeDefinitionName []
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "/robheghan/dummy/mod1/bump-version"
                                      , metadata = Metadata.default
                                      , implementation =
                                            Qualifier.SoloImpl
                                                [ Qualifier.Integer emptyRange 1
                                                , Qualifier.Builtin emptyRange Builtin.Plus
                                                ]
                                      }
                                    , { name = "/robheghan/dummy/mod2/version"
                                      , metadata = Metadata.default
                                      , implementation =
                                            Qualifier.SoloImpl
                                                [ Qualifier.Integer emptyRange 5
                                                ]
                                      }
                                    , { name = "/robheghan/dummy/mod3/next-version"
                                      , metadata = Metadata.default
                                      , implementation =
                                            Qualifier.SoloImpl
                                                [ Qualifier.Word emptyRange "/robheghan/dummy/mod2/version"
                                                , Qualifier.Word emptyRange "/robheghan/dummy/mod1/bump-version"
                                                ]
                                      }
                                    ]
                            }
                            (Util.stripLocations ast)
        , test "Specified entry point is marked as such" <|
            \_ ->
                let
                    loaderResult =
                        PackageLoader.init
................................................................................
            Expect.equalLists [] (sfDiff ++ sfDiffRev)


resolveSideEffects :
    Dict String String
    -> List PackageLoader.SideEffect
    -> PackageLoader.Model
    -> Result String ( List PackageLoader.SideEffect, Qualifier.AST )
resolveSideEffects fileSystem seenSfs model =
    case PackageLoader.getSideEffect model of
        Nothing ->
            case model of
                PackageLoader.Done ast ->
                    Ok ( seenSfs, ast )

................................................................................
        case pathParts of
            [ _, "play.json" ] ->
                True

            _ ->
                False


stdLibFiles : Dict String String
stdLibFiles =
    Dict.fromList
        [ ( "/project/lib/unused/play.json"
          , """
            {
                "name": "some/useless",
                "version": "1.7.0",
                "language-version": "0.2.0",
                "exposed-modules": [
                    "useless/mod"
                ],
                "dependencies": {
                },
                "package-paths": [
                ]
            }
          """
          )
        , ( "/project/lib/unused/src/useless/mod.play"
          , """
            def: square
            : dup *
            """
          )
        ]


testFiles : Dict String String
testFiles =
    Dict.fromList
        [ ( "/project/play.json"
          , """
            {
................................................................................
          )
        , ( "/project/lib/template_strings/src/template_strings/mod.play"
          , """
            def: dec
            : 1 =
            """
          )






















        , ( "/project/lib/version/play.json"
          , """
            {
                "name": "play/version",
                "version": "1.0.0",
                "language-version": "0.2.0",
                "exposed-modules": [
................................................................................
        , ( "/project/lib/template_strings/lib/version/src/version/data.play"
          , """
            def: number
            : 2
            """
          )
        ]
        |> Dict.union stdLibFiles


testFilesInternalConsistency : Dict String String
testFilesInternalConsistency =
    Dict.fromList
        [ ( "/project/play.json"
          , """
            {
                "name": "robheghan/dummy",
                "version": "1.0.0",
                "language-version": "0.2.0",
                "exposed-modules": [
                    "mod1",
                    "mod2",
                    "mod3"
                ],
                "dependencies": {},
                "package-paths": []
            }
            """
          )
        , ( "/project/src/mod1.play"
          , """
            def: bump-version
            : 1 +
            """
          )
        , ( "/project/src/mod2.play"
          , """
            def: version
            : 5
            """
          )
        , ( "/project/src/mod3.play"
          , """
            def: next-version
            : mod2/version mod1/bump-version
            """
          )
        ]
        |> Dict.union stdLibFiles

Modified tests/Test/Parser.elm from [a9f19ae62c] to [e119fc8848].

1
2
3
4
5
6


7
8


9

10




11


12
13
14
15
16
17
18
..
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
..
86
87
88
89
90
91
92

93
94
95
96
97
98
99
100
101
102





103
104
105
106
107
108
109
...
126
127
128
129
130
131
132

133
134
135
136
137
138
139
140
141
142
143
144
145
146
147





148
149
150
151
152
153
154
...
166
167
168
169
170
171
172

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188





189
190
191
192
193
194
195

196
197




198
199
200
201
202
203
204
205

206




207
208
209
210
211
212
213
...
224
225
226
227
228
229
230

231
232
233
234
235
236
237
238
239




240
241
242
243
244
245
246
...
269
270
271
272
273
274
275

276
277
278
279
280
281
282
283
284
285
286
287
288
289
290



291
292
293
294
295
296
297
298
299
300
301
302
303
...
324
325
326
327
328
329
330

331
332
333
334
335
336
337
338
339
340
341
342
343
344



345
346
347
348
349
350
351
352
353
354
355
356
357
...
381
382
383
384
385
386
387

388
389
390
391
392
393
394
395
396
397
398
399
400
401
402



403
404
405
406
407
408
409
410
411
412
413
414
415
...
440
441
442
443
444
445
446

447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465




466
467
468
469
470
471
472
473
474
475
476
477
478
...
491
492
493
494
495
496
497
498
499
500
501
502

503
504
505
506
507
508
509
510
511



512
513





514
515
516
517
518
519
520
521
522

523
524
525
526
527
528
529
...
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
...
606
607
608
609
610
611
612

613
614
615
616
617



618
619
620
621


622
623
624
625
626
627
628
...
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
...
687
688
689
690
691
692
693

694
695
696
697
698



699
700
701
702
703
704
705
706
707
708
709
...
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731

732
733
734
735
736



737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759

760
761
762
763
764



765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

788
789
790
791
792



793
794
795
796
797
798
799
800
801
802
803
804
805














































































































































































806
807
808
809
810
811
812
...
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
...
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
...
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
...
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
....
1022
1023
1024
1025
1026
1027
1028














1029












































































































module Test.Parser exposing (..)

import Dict
import Dict.Extra as Dict
import Expect
import Play.Data.Metadata as Metadata


import Play.Data.SourceLocation exposing (SourceLocation, SourceLocationRange, emptyRange)
import Play.Data.Type as Type


import Play.Parser as AST exposing (..)

import Test exposing (Test, describe, test)




import Test.Parser.Util exposing (addFunctionsForStructs, compile, compileRetainLocations, expectCompiles)




suite : Test
suite =
    describe "Parser"
        [ test "Sample program" <|
            \_ ->
................................................................................
                        : 1 +

                        def: dec
                        type: Int -- Int
                        : 1 -

                        def: main
                        entry: true
                        : 1 inc inc dec 2 =
                        """

                    expectedAst =

                        { types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "inc"
                                  , metadata = Metadata.default



                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "+"
                                            ]
                                  }
                                , { name = "dec"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [ Type.Int ] [ Type.Int ]





                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "-"
                                            ]
                                  }
                                , { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.asEntryPoint

                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "inc"
                                            , AST.Word emptyRange "inc"
                                            , AST.Word emptyRange "dec"
                                            , AST.Integer emptyRange 2
                                            , AST.Word emptyRange "="
                                            ]
                                  }
                                ]
                        }
































































































                in
                case compile source of
                    Err _ ->
                        Expect.fail "Did not expect parsing to fail"

                    Ok ast ->
                        Expect.equal expectedAst ast
................................................................................
                            
                            def: as-int
                            type: True -- Int
                            : 1
                            """

                        expectedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ CustomTypeDef emptyRange "True" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "as-int"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType [ Type.Custom "True" ] [ Type.Int ]





                                      , implementation =
                                            SoloImpl
                                                [ AST.Integer emptyRange 1
                                                ]
                                      }
                                    ]
                            }
................................................................................

                            def: get-age
                            type: Person -- Int
                            : age>
                            """

                        expectedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ CustomTypeDef emptyRange
                                        "Person"
                                        []
                                        [ ( "age", Type.Int )
                                        , ( "jobs", Type.Int )
                                        ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "get-age"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType [ Type.Custom "Person" ] [ Type.Int ]





                                      , implementation =
                                            SoloImpl
                                                [ AST.Word emptyRange "age>"
                                                ]
                                      }
                                    ]
                            }
................................................................................
                        source =
                            """
                            defstruct: Box a
                            : element a
                            """

                        expectedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ CustomTypeDef emptyRange
                                        "Box"
                                        [ "a" ]
                                        [ ( "element", Type.Generic "a" )
                                        ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = ">Box"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withVerifiedType
                                                    [ Type.Generic "a" ]
                                                    [ Type.CustomGeneric "Box" [ Type.Generic "a" ] ]





                                      , implementation =
                                            SoloImpl [ AST.ConstructType "Box" ]
                                      }
                                    , { name = ">element"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withVerifiedType

                                                    [ Type.CustomGeneric "Box" [ Type.Generic "a" ], Type.Generic "a" ]
                                                    [ Type.CustomGeneric "Box" [ Type.Generic "a" ] ]




                                      , implementation =
                                            SoloImpl [ AST.SetMember "Box" "element" ]
                                      }
                                    , { name = "element>"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withVerifiedType
                                                    [ Type.CustomGeneric "Box" [ Type.Generic "a" ] ]

                                                    [ Type.Generic "a" ]




                                      , implementation =
                                            SoloImpl [ AST.GetMember "Box" "element" ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
................................................................................
                        """
                        def: over
                        type: a b -- a b a
                        : dup rotate
                        """

                    expectedAst =

                        { types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "over"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType
                                                [ Type.Generic "a", Type.Generic "b" ]
                                                [ Type.Generic "a", Type.Generic "b", Type.Generic "a" ]




                                  , implementation =
                                        SoloImpl
                                            [ AST.Word emptyRange "dup"
                                            , AST.Word emptyRange "rotate"
                                            ]
                                  }
                                ]
................................................................................
                            : True
                              drop 1
                            : False
                              drop 0
                            """

                        expectedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ UnionTypeDef emptyRange
                                        "Bool"
                                        []
                                        [ Type.Custom "True"
                                        , Type.Custom "False"
                                        ]
                                    , CustomTypeDef emptyRange "True" [] []
                                    , CustomTypeDef emptyRange "False" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "to-int"
                                      , metadata = Metadata.default



                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Type.Custom "True") []
                                                  , [ AST.Word emptyRange "drop", AST.Integer emptyRange 1 ]
                                                  )
                                                , ( TypeMatch emptyRange (Type.Custom "False") []
                                                  , [ AST.Word emptyRange "drop", AST.Integer emptyRange 0 ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                            : a
                              !
                            : Nil
                              drop
                            """

                        expectedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ UnionTypeDef emptyRange
                                        "Maybe"
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nil"
                                        ]
                                    , CustomTypeDef emptyRange "Nil" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "if-present"
                                      , metadata = Metadata.default



                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Type.Generic "a") []
                                                  , [ AST.Word emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (Type.Custom "Nil") []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                            : (Box a)
                              !
                            : Nil
                              drop
                            """

                        expectedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ UnionTypeDef emptyRange
                                        "MaybeBox"
                                        [ "a" ]
                                        [ Type.CustomGeneric "Box" [ Type.Generic "a" ]
                                        , Type.Custom "Nil"
                                        ]
                                    , CustomTypeDef emptyRange "Box" [ "a" ] [ ( "element", Type.Generic "a" ) ]
                                    , CustomTypeDef emptyRange "Nil" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "if-present"
                                      , metadata = Metadata.default



                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Type.CustomGeneric "Box" [ Type.Generic "a" ]) []
                                                  , [ AST.Word emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (Type.Custom "Nil") []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                            : (Box a)
                              !
                            : Nil
                              drop
                            """

                        expectedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ UnionTypeDef emptyRange
                                        "MaybeBox"
                                        [ "a" ]
                                        [ Type.CustomGeneric "Box" [ Type.Generic "a" ]
                                        , Type.Custom "Nil"
                                        ]
                                    , CustomTypeDef emptyRange "Box" [ "a" ] [ ( "element", Type.Generic "a" ) ]
                                    , CustomTypeDef emptyRange "Nil" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "if-present"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
                                                    [ Type.CustomGeneric "MaybeBox" [ Type.Generic "a" ], Type.Generic "a" ]
                                                    [ Type.Generic "a" ]




                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Type.CustomGeneric "Box" [ Type.Generic "a" ]) []
                                                  , [ AST.Word emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (Type.Custom "Nil") []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                    source =
                        """
                        def: apply-to-num
                        type: Int [ Int -- Int ] -- Int
                        : !

                        def: main
                        entry: true
                        : 1 [ 1 + ] apply-to-num
                        """

                    expectedAst =

                        { types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "apply-to-num"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType
                                                [ Type.Int
                                                , Type.Quotation { input = [ Type.Int ], output = [ Type.Int ] }



                                                ]
                                                [ Type.Int ]





                                  , implementation =
                                        SoloImpl
                                            [ AST.Word emptyRange "!"
                                            ]
                                  }
                                , { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.asEntryPoint

                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Quotation
                                                emptyRange
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
................................................................................
                    source =
                        """
                        def: apply-to-num
                        type: a... [ a... -- b... ] -- b...
                        : !

                        def: main
                        entry: true
                        : 1 [ 1 + ] apply-to-num
                        """

                    expectedAst =

                        { types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "apply-to-num"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType
                                                [ Type.StackRange "a"
                                                , Type.Quotation
                                                    { input = [ Type.StackRange "a" ]
                                                    , output = [ Type.StackRange "b" ]
                                                    }
                                                ]
                                                [ Type.StackRange "b" ]




                                  , implementation =
                                        SoloImpl
                                            [ AST.Word emptyRange "!"
                                            ]
                                  }
                                , { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.asEntryPoint

                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Quotation emptyRange
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
................................................................................
                            defmulti: zero?
                            : Int( value 0 )
                              True
                            else: False
                            """

                        expectedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "zero?"
                                      , metadata = Metadata.default



                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange
                                                        Type.Int


                                                        [ ( "value", AST.LiteralInt 0 )
                                                        ]
                                                  , [ AST.Word emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "False" ]
                                      }
................................................................................
                            defmulti: pair?
                            : List( tail List( tail Nil ) )
                              True
                            else: False
                            """

                        expectedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "pair?"
                                      , metadata = Metadata.default



                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange
                                                        (Type.Custom "List")
                                                        [ ( "tail"
                                                          , AST.RecursiveMatch
                                                                (TypeMatch emptyRange
                                                                    (Type.Custom "List")
                                                                    [ ( "tail", AST.LiteralType (Type.Custom "Nil") )
                                                                    ]
                                                                )
                                                          )
                                                        ]
                                                  , [ AST.Word emptyRange "True" ]
                                                  )
                                                ]
................................................................................
                            defmulti: origo?
                            : Pair( first 0 second 0 )
                              True
                            else: False
                            """

                        expectedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "origo?"
                                      , metadata = Metadata.default



                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange
                                                        (Type.Custom "Pair")
                                                        [ ( "first", AST.LiteralInt 0 )
                                                        , ( "second", AST.LiteralInt 0 )
                                                        ]
                                                  , [ AST.Word emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "False" ]
................................................................................
                    case compile source of
                        Err _ ->
                            Expect.fail "Did not expect parsing to fail"

                        Ok ast ->
                            Expect.equal expectedAst ast
            ]
        , describe "modules" <|
            [ test "internal reference" <|
                \_ ->
                    let
                        source =
                            """
                            def: test
                            : some/module/sample
                            """

                        expectedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , metadata = Metadata.default



                                      , implementation =
                                            SoloImpl
                                                [ AST.PackageWord emptyRange [ "some", "module" ] "sample" ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err _ ->
                            Expect.fail "Did not expect parsing to fail"

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "external reference" <|
                \_ ->
                    let
                        source =
                            """
                            def: test
                            : /some/module/sample
                            """

                        expectedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , metadata = Metadata.default



                                      , implementation =
                                            SoloImpl
                                                [ AST.ExternalWord emptyRange [ "some", "module" ] "sample" ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err _ ->
                            Expect.fail "Did not expect parsing to fail"

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "internal _and_ external reference" <|
                \_ ->
                    let
                        source =
                            """
                            def: test
                            : internal/sample /some/module/sample
                            """

                        expectedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , metadata = Metadata.default



                                      , implementation =
                                            SoloImpl
                                                [ AST.PackageWord emptyRange [ "internal" ] "sample"
                                                , AST.ExternalWord emptyRange [ "some", "module" ] "sample"
                                                ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err _ ->
                            Expect.fail "Did not expect parsing to fail"















































































































































































                        Ok ast ->
                            Expect.equal expectedAst ast
            ]
        , test "Support code comments" <|
            \_ ->
                expectCompiles
                    """
................................................................................
                    : 1
                      # + wouldnt work here
                      -

                    # And thats it!
                     # wonder what else we should do...
                    """
        , test "definition without implementation should be legal" <|
            \_ ->
                expectCompiles
                    """
                    def: someword
                    """
        , test "Correct line information" <|
            \_ ->
................................................................................
                          False
                        else: True
                        """

                    -- The ending source location for most definitions now ends where the next definition beings
                    -- This is not what we want (it includes too much white space), but it'll do for now.
                    expectedAst =

                        { types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ UnionTypeDef
                                    (SourceLocationRange
                                        (SourceLocation 2 1 1)
                                        (SourceLocation 6 1 32)
                                    )
                                    "Bool"
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , CustomTypeDef
                                    (SourceLocationRange
                                        (SourceLocation 6 1 32)
                                        (SourceLocation 7 1 48)
                                    )
                                    "True"
................................................................................
                                    "False"
                                    []
                                    []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "True"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withVerifiedType [] [ Type.Custom "True" ]





                                  , implementation = SoloImpl [ ConstructType "True" ]
                                  }
                                , { name = "False"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withVerifiedType [] [ Type.Custom "False" ]





                                  , implementation = SoloImpl [ ConstructType "False" ]
                                  }
                                , { name = "from-int"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [ Type.Int ] [ Type.Int ]





                                            |> Metadata.withSourceLocationRange

                                                (SourceLocationRange
                                                    (SourceLocation 9 1 66)
                                                    (SourceLocation 16 1 141)
                                                )


                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 11 3 104)
                                                        (SourceLocation 11 17 118)
                                                    )
                                                    Type.Int
                                                    [ ( "value", LiteralInt 0 ) ]
                                              , [ Word
                                                    (SourceLocationRange
                                                        (SourceLocation 12 3 121)
                                                        (SourceLocation 13 1 127)
                                                    )
                                                    "False"
................................................................................
                                                ]
                                              )
                                            , ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 13 3 129)
                                                        (SourceLocation 14 3 135)
                                                    )
                                                    Type.Int
                                                    []
                                              , [ Word
                                                    (SourceLocationRange
                                                        (SourceLocation 14 3 135)
                                                        (SourceLocation 16 1 141)
                                                    )
                                                    "True"
                                                ]
                                              )
                                            ]
                                            []
                                  }
                                , { name = "equal"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withSourceLocationRange

                                                (SourceLocationRange
                                                    (SourceLocation 16 1 141)
                                                    (SourceLocation 19 1 170)
                                                )


                                  , implementation =
                                        SoloImpl
                                            [ Word
                                                (SourceLocationRange
                                                    (SourceLocation 17 3 154)
                                                    (SourceLocation 17 5 156)
                                                )
................................................................................
                                                    (SourceLocation 17 14 165)
                                                    (SourceLocation 19 1 170)
                                                )
                                                "not"
                                            ]
                                  }
                                , { name = "not"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withSourceLocationRange

                                                (SourceLocationRange
                                                    (SourceLocation 19 1 170)
                                                    (SourceLocation 23 1 210)
                                                )


                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 20 3 186)
                                                        (SourceLocation 21 3 193)
                                                    )
                                                    (Type.Custom "True")
                                                    []
                                              , [ Word
                                                    (SourceLocationRange
                                                        (SourceLocation 21 3 193)
                                                        (SourceLocation 22 1 199)
                                                    )
                                                    "False"
................................................................................
                in
                case compileRetainLocations source of
                    Err _ ->
                        Expect.fail "Did not expect compilation to fail."

                    Ok ast ->
                        Expect.equal expectedAst ast














        ]

















































































































|
>
>
|
<
>
>

>

>
>
>
>
|
>
>







 







<




>
|



|
>
>
>







|
|
|
>
>
>
>
>







|
|
|
>












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







 







>
|






|
|
|
>
>
>
>
>







 







>
|




|
|





|
|
|
>
>
>
>
>







 







>
|




|





|
<
|
|
<
>
>
>
>
>




|
<
|
>
|
<
>
>
>
>




|
<
|
<
>
|
>
>
>
>







 







>
|



|
|
|
|
<
>
>
>
>







 







>
|




|
|







|
>
>
>


|


|







 







>
|




|
|






|
>
>
>


|


|







 







>
|




|
|

|





|
>
>
>


|


|







 







>
|




|
|

|





|
|
|
<
|
>
>
>
>


|


|







 







<




>
|



|
|
|
|
|
>
>
>

<
>
>
>
>
>






|
|
|
>







 







<




>
|



|
|
|
|
|
|
|


|
>
>
>
>






|
|
|
>







 







>
|



|
>
>
>


|
<
>
>







 







>
|



|
>
>
>



|



|
|







 







>
|



|
>
>
>



|







 







|
|









>
|



|
>
>
>













|









>
|



|
>
>
>













|









>
|



|
>
>
>













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







 







|







 







>
|








|
|







 







|
|
|
>
>
>
>
>



|
|
|
>
>
>
>
>



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







|







 







|













|
<
|
>
|
|
|
|
>
>







 







|
<
|
>
|
|
|
|
>
>







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
..
33
34
35
36
37
38
39

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
...
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
...
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
...
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312

313
314

315
316
317
318
319
320
321
322
323
324

325
326
327

328
329
330
331
332
333
334
335
336

337

338
339
340
341
342
343
344
345
346
347
348
349
350
...
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376

377
378
379
380
381
382
383
384
385
386
387
...
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
...
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
...
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
...
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
...
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
...
711
712
713
714
715
716
717

718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
...
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794

795
796
797
798
799
800
801
802
803
...
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
...
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
...
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
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
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
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
....
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
....
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
....
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
1289
1290
1291
1292



1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
....
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
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
....
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
1396
1397
....
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
module Test.Parser exposing (..)

import Dict
import Dict.Extra as Dict
import Expect
import Play.Data.SourceLocation
    exposing
        ( SourceLocation
        , SourceLocationRange

        , emptyRange
        )
import Play.Parser as AST exposing (..)
import Set
import Test exposing (Test, describe, test)
import Test.Parser.Util
    exposing
        ( addFunctionsForStructs
        , compile
        , compileRetainLocations
        , expectCompiles
        )


suite : Test
suite =
    describe "Parser"
        [ test "Sample program" <|
            \_ ->
................................................................................
                        : 1 +

                        def: dec
                        type: Int -- Int
                        : 1 -

                        def: main

                        : 1 inc inc dec 2 =
                        """

                    expectedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "inc"
                                  , typeSignature = NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "+"
                                            ]
                                  }
                                , { name = "dec"
                                  , typeSignature =
                                        UserProvided
                                            { input = [ LocalRef "Int" [] ]
                                            , output = [ LocalRef "Int" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "-"
                                            ]
                                  }
                                , { name = "main"
                                  , typeSignature = NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "inc"
                                            , AST.Word emptyRange "inc"
                                            , AST.Word emptyRange "dec"
                                            , AST.Integer emptyRange 2
                                            , AST.Word emptyRange "="
                                            ]
                                  }
                                ]
                        }
                in
                case compile source of
                    Err _ ->
                        Expect.fail "Did not expect parsing to fail"

                    Ok ast ->
                        Expect.equal expectedAst ast
        , test "Multi args and type signature" <|
            \_ ->
                let
                    source =
                        """
                        def: int=
                        type: Int Int -- Bool
                        : - zero?
                        """

                    expectedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "int="
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.LocalRef "Int" [], AST.LocalRef "Int" [] ]
                                            , output = [ AST.LocalRef "Bool" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Word emptyRange "-"
                                            , AST.Word emptyRange "zero?"
                                            ]
                                  }
                                ]
                        }
                in
                case compile source of
                    Err _ ->
                        Expect.fail "Did not expect parsing to fail"

                    Ok ast ->
                        Expect.equal expectedAst ast
        , test ", is a valid fn name" <|
            \_ ->
                let
                    source =
                        """
                        def: ,
                        type: Int Int -- Int
                        : +

                        def: add2
                        type: Int -- Int
                        : 2 ,
                        """

                    expectedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = ","
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.LocalRef "Int" [], AST.LocalRef "Int" [] ]
                                            , output = [ AST.LocalRef "Int" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Word emptyRange "+"
                                            ]
                                  }
                                , { name = "add2"
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.LocalRef "Int" [] ]
                                            , output = [ AST.LocalRef "Int" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 2
                                            , AST.Word emptyRange ","
                                            ]
                                  }
                                ]
                        }
                in
                case compile source of
                    Err _ ->
                        Expect.fail "Did not expect parsing to fail"

                    Ok ast ->
                        Expect.equal expectedAst ast
................................................................................
                            
                            def: as-int
                            type: True -- Int
                            : 1
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ CustomTypeDef emptyRange "True" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "as-int"
                                      , typeSignature =
                                            UserProvided
                                                { input = [ LocalRef "True" [] ]
                                                , output = [ LocalRef "Int" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl
                                                [ AST.Integer emptyRange 1
                                                ]
                                      }
                                    ]
                            }
................................................................................

                            def: get-age
                            type: Person -- Int
                            : age>
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ CustomTypeDef emptyRange
                                        "Person"
                                        []
                                        [ ( "age", LocalRef "Int" [] )
                                        , ( "jobs", LocalRef "Int" [] )
                                        ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "get-age"
                                      , typeSignature =
                                            UserProvided
                                                { input = [ LocalRef "Person" [] ]
                                                , output = [ LocalRef "Int" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl
                                                [ AST.Word emptyRange "age>"
                                                ]
                                      }
                                    ]
                            }
................................................................................
                        source =
                            """
                            defstruct: Box a
                            : element a
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ CustomTypeDef emptyRange
                                        "Box"
                                        [ "a" ]
                                        [ ( "element", Generic "a" )
                                        ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = ">Box"
                                      , typeSignature =

                                            Verified
                                                { input = [ Generic "a" ]

                                                , output = [ LocalRef "Box" [ Generic "a" ] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl [ AST.ConstructType "Box" ]
                                      }
                                    , { name = ">element"
                                      , typeSignature =

                                            Verified
                                                { input = [ LocalRef "Box" [ Generic "a" ], Generic "a" ]
                                                , output = [ LocalRef "Box" [ Generic "a" ] ]

                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl [ AST.SetMember "Box" "element" ]
                                      }
                                    , { name = "element>"
                                      , typeSignature =

                                            Verified

                                                { input = [ LocalRef "Box" [ Generic "a" ] ]
                                                , output = [ Generic "a" ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl [ AST.GetMember "Box" "element" ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
................................................................................
                        """
                        def: over
                        type: a b -- a b a
                        : dup rotate
                        """

                    expectedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "over"
                                  , typeSignature =
                                        UserProvided
                                            { input = [ Generic "a", Generic "b" ]
                                            , output = [ Generic "a", Generic "b", Generic "a" ]

                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Word emptyRange "dup"
                                            , AST.Word emptyRange "rotate"
                                            ]
                                  }
                                ]
................................................................................
                            : True
                              drop 1
                            : False
                              drop 0
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ UnionTypeDef emptyRange
                                        "Bool"
                                        []
                                        [ LocalRef "True" []
                                        , LocalRef "False" []
                                        ]
                                    , CustomTypeDef emptyRange "True" [] []
                                    , CustomTypeDef emptyRange "False" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "to-int"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (LocalRef "True" []) []
                                                  , [ AST.Word emptyRange "drop", AST.Integer emptyRange 1 ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "False" []) []
                                                  , [ AST.Word emptyRange "drop", AST.Integer emptyRange 0 ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                            : a
                              !
                            : Nil
                              drop
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ UnionTypeDef emptyRange
                                        "Maybe"
                                        [ "a" ]
                                        [ Generic "a"
                                        , LocalRef "Nil" []
                                        ]
                                    , CustomTypeDef emptyRange "Nil" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "if-present"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Generic "a") []
                                                  , [ AST.Word emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                            : (Box a)
                              !
                            : Nil
                              drop
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ UnionTypeDef emptyRange
                                        "MaybeBox"
                                        [ "a" ]
                                        [ LocalRef "Box" [ Generic "a" ]
                                        , LocalRef "Nil" []
                                        ]
                                    , CustomTypeDef emptyRange "Box" [ "a" ] [ ( "element", Generic "a" ) ]
                                    , CustomTypeDef emptyRange "Nil" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "if-present"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (LocalRef "Box" [ Generic "a" ]) []
                                                  , [ AST.Word emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                            : (Box a)
                              !
                            : Nil
                              drop
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ UnionTypeDef emptyRange
                                        "MaybeBox"
                                        [ "a" ]
                                        [ LocalRef "Box" [ Generic "a" ]
                                        , LocalRef "Nil" []
                                        ]
                                    , CustomTypeDef emptyRange "Box" [ "a" ] [ ( "element", Generic "a" ) ]
                                    , CustomTypeDef emptyRange "Nil" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "if-present"
                                      , typeSignature =
                                            UserProvided
                                                { input = [ LocalRef "MaybeBox" [ Generic "a" ], Generic "a" ]

                                                , output = [ Generic "a" ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (LocalRef "Box" [ Generic "a" ]) []
                                                  , [ AST.Word emptyRange "!" ]
                                                  )
                                                , ( TypeMatch emptyRange (LocalRef "Nil" []) []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                []
                                      }
                                    ]
                            }
................................................................................
                    source =
                        """
                        def: apply-to-num
                        type: Int [ Int -- Int ] -- Int
                        : !

                        def: main

                        : 1 [ 1 + ] apply-to-num
                        """

                    expectedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "apply-to-num"
                                  , typeSignature =
                                        UserProvided
                                            { input =
                                                [ LocalRef "Int" []
                                                , QuotationType
                                                    { input = [ LocalRef "Int" [] ]
                                                    , output = [ LocalRef "Int" [] ]
                                                    }
                                                ]

                                            , output = [ LocalRef "Int" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Word emptyRange "!"
                                            ]
                                  }
                                , { name = "main"
                                  , typeSignature = NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Quotation
                                                emptyRange
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
................................................................................
                    source =
                        """
                        def: apply-to-num
                        type: a... [ a... -- b... ] -- b...
                        : !

                        def: main

                        : 1 [ 1 + ] apply-to-num
                        """

                    expectedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "apply-to-num"
                                  , typeSignature =
                                        UserProvided
                                            { input =
                                                [ StackRange "a"
                                                , QuotationType
                                                    { input = [ StackRange "a" ]
                                                    , output = [ StackRange "b" ]
                                                    }
                                                ]
                                            , output = [ StackRange "b" ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Word emptyRange "!"
                                            ]
                                  }
                                , { name = "main"
                                  , typeSignature = NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Quotation emptyRange
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
................................................................................
                            defmulti: zero?
                            : Int( value 0 )
                              True
                            else: False
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "zero?"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch

                                                        emptyRange
                                                        (LocalRef "Int" [])
                                                        [ ( "value", AST.LiteralInt 0 )
                                                        ]
                                                  , [ AST.Word emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "False" ]
                                      }
................................................................................
                            defmulti: pair?
                            : List( tail List( tail Nil ) )
                              True
                            else: False
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "pair?"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , 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.Word emptyRange "True" ]
                                                  )
                                                ]
................................................................................
                            defmulti: origo?
                            : Pair( first 0 second 0 )
                              True
                            else: False
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "origo?"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange
                                                        (LocalRef "Pair" [])
                                                        [ ( "first", AST.LiteralInt 0 )
                                                        , ( "second", AST.LiteralInt 0 )
                                                        ]
                                                  , [ AST.Word emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "False" ]
................................................................................
                    case compile source of
                        Err _ ->
                            Expect.fail "Did not expect parsing to fail"

                        Ok ast ->
                            Expect.equal expectedAst ast
            ]
        , describe "Modules" <|
            [ test "Internal word reference" <|
                \_ ->
                    let
                        source =
                            """
                            def: test
                            : some/module/sample
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl
                                                [ AST.PackageWord emptyRange [ "some", "module" ] "sample" ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err _ ->
                            Expect.fail "Did not expect parsing to fail"

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "External word reference" <|
                \_ ->
                    let
                        source =
                            """
                            def: test
                            : /some/module/sample
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl
                                                [ AST.ExternalWord emptyRange [ "some", "module" ] "sample" ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err _ ->
                            Expect.fail "Did not expect parsing to fail"

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "Internal _and_ external word reference" <|
                \_ ->
                    let
                        source =
                            """
                            def: test
                            : internal/sample /some/module/sample
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl
                                                [ AST.PackageWord emptyRange [ "internal" ] "sample"
                                                , AST.ExternalWord emptyRange [ "some", "module" ] "sample"
                                                ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err _ ->
                            Expect.fail "Did not expect parsing to fail"

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "Internal types in type signature" <|
                \_ ->
                    let
                        source =
                            """
                            def: test
                            type: internal/Tipe -- Int
                            : drop 1
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , typeSignature =
                                            UserProvided
                                                { input = [ InternalRef [ "internal" ] "Tipe" [] ]
                                                , output = [ LocalRef "Int" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl
                                                [ AST.Word emptyRange "drop"
                                                , AST.Integer emptyRange 1
                                                ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err err ->
                            Expect.fail <| "Did not expect parsing to fail: " ++ Debug.toString err

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "External types in type signature" <|
                \_ ->
                    let
                        source =
                            """
                            def: test
                            type: /external/Tipe -- Int
                            : drop 1
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , typeSignature =
                                            UserProvided
                                                { input = [ ExternalRef [ "external" ] "Tipe" [] ]
                                                , output = [ LocalRef "Int" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl
                                                [ AST.Word emptyRange "drop"
                                                , AST.Integer emptyRange 1
                                                ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err err ->
                            Expect.fail <| "Did not expect parsing to fail: " ++ Debug.toString err

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "External type in multifn" <|
                \_ ->
                    let
                        source =
                            """
                            defmulti: test
                            type: /external/Tipe -- Int
                            : /external/Tipe( value 1 )
                              drop 1
                            else:
                              drop 0
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , typeSignature =
                                            UserProvided
                                                { input = [ ExternalRef [ "external" ] "Tipe" [] ]
                                                , output = [ LocalRef "Int" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (ExternalRef [ "external" ] "Tipe" []) [ ( "value", LiteralInt 1 ) ]
                                                  , [ AST.Word emptyRange "drop"
                                                    , AST.Integer emptyRange 1
                                                    ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "drop"
                                                , AST.Integer emptyRange 0
                                                ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err err ->
                            Expect.fail <| "Did not expect parsing to fail: " ++ Debug.toString err

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "Internal type in multifn" <|
                \_ ->
                    let
                        source =
                            """
                            defmulti: test
                            type: internal/Tipe -- Int
                            : internal/Tipe( value 1 )
                              drop 1
                            else:
                              drop 0
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "test"
                                      , typeSignature =
                                            UserProvided
                                                { input = [ InternalRef [ "internal" ] "Tipe" [] ]
                                                , output = [ LocalRef "Int" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (InternalRef [ "internal" ] "Tipe" []) [ ( "value", LiteralInt 1 ) ]
                                                  , [ AST.Word emptyRange "drop"
                                                    , AST.Integer emptyRange 1
                                                    ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "drop"
                                                , AST.Integer emptyRange 0
                                                ]
                                      }
                                    ]
                            }
                    in
                    case compile source of
                        Err err ->
                            Expect.fail <| "Did not expect parsing to fail: " ++ Debug.toString err

                        Ok ast ->
                            Expect.equal expectedAst ast
            ]
        , test "Support code comments" <|
            \_ ->
                expectCompiles
                    """
................................................................................
                    : 1
                      # + wouldnt work here
                      -

                    # And thats it!
                     # wonder what else we should do...
                    """
        , test "Definition without implementation should be legal" <|
            \_ ->
                expectCompiles
                    """
                    def: someword
                    """
        , test "Correct line information" <|
            \_ ->
................................................................................
                          False
                        else: True
                        """

                    -- The ending source location for most definitions now ends where the next definition beings
                    -- This is not what we want (it includes too much white space), but it'll do for now.
                    expectedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ UnionTypeDef
                                    (SourceLocationRange
                                        (SourceLocation 2 1 1)
                                        (SourceLocation 6 1 32)
                                    )
                                    "Bool"
                                    []
                                    [ LocalRef "True" []
                                    , LocalRef "False" []
                                    ]
                                , CustomTypeDef
                                    (SourceLocationRange
                                        (SourceLocation 6 1 32)
                                        (SourceLocation 7 1 48)
                                    )
                                    "True"
................................................................................
                                    "False"
                                    []
                                    []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "True"
                                  , typeSignature =
                                        Verified
                                            { input = []
                                            , output = [ LocalRef "True" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation = SoloImpl [ ConstructType "True" ]
                                  }
                                , { name = "False"
                                  , typeSignature =
                                        Verified
                                            { input = []
                                            , output = [ LocalRef "False" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation = SoloImpl [ ConstructType "False" ]
                                  }
                                , { name = "from-int"



                                  , typeSignature =
                                        UserProvided
                                            { input = [ LocalRef "Int" [] ]
                                            , output = [ LocalRef "Int" [] ]
                                            }
                                  , sourceLocationRange =
                                        Just
                                            (SourceLocationRange
                                                (SourceLocation 9 1 66)
                                                (SourceLocation 16 1 141)
                                            )
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 11 3 104)
                                                        (SourceLocation 11 17 118)
                                                    )
                                                    (LocalRef "Int" [])
                                                    [ ( "value", LiteralInt 0 ) ]
                                              , [ Word
                                                    (SourceLocationRange
                                                        (SourceLocation 12 3 121)
                                                        (SourceLocation 13 1 127)
                                                    )
                                                    "False"
................................................................................
                                                ]
                                              )
                                            , ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 13 3 129)
                                                        (SourceLocation 14 3 135)
                                                    )
                                                    (LocalRef "Int" [])
                                                    []
                                              , [ Word
                                                    (SourceLocationRange
                                                        (SourceLocation 14 3 135)
                                                        (SourceLocation 16 1 141)
                                                    )
                                                    "True"
                                                ]
                                              )
                                            ]
                                            []
                                  }
                                , { name = "equal"
                                  , typeSignature = NotProvided

                                  , sourceLocationRange =
                                        Just
                                            (SourceLocationRange
                                                (SourceLocation 16 1 141)
                                                (SourceLocation 19 1 170)
                                            )
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ Word
                                                (SourceLocationRange
                                                    (SourceLocation 17 3 154)
                                                    (SourceLocation 17 5 156)
                                                )
................................................................................
                                                    (SourceLocation 17 14 165)
                                                    (SourceLocation 19 1 170)
                                                )
                                                "not"
                                            ]
                                  }
                                , { name = "not"
                                  , typeSignature = NotProvided

                                  , sourceLocationRange =
                                        Just
                                            (SourceLocationRange
                                                (SourceLocation 19 1 170)
                                                (SourceLocation 23 1 210)
                                            )
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        MultiImpl
                                            [ ( TypeMatch
                                                    (SourceLocationRange
                                                        (SourceLocation 20 3 186)
                                                        (SourceLocation 21 3 193)
                                                    )
                                                    (LocalRef "True" [])
                                                    []
                                              , [ Word
                                                    (SourceLocationRange
                                                        (SourceLocation 21 3 193)
                                                        (SourceLocation 22 1 199)
                                                    )
                                                    "False"
................................................................................
                in
                case compileRetainLocations source of
                    Err _ ->
                        Expect.fail "Did not expect compilation to fail."

                    Ok ast ->
                        Expect.equal expectedAst ast
        , describe "Module definitions"
            [ test "Imports and aliases" <|
                \_ ->
                    let
                        source =
                            """
                            defmodule:
                            alias: other /some/mod
                            alias: moar local/mod
                            import: /some/other/mod test1 word2
                            import: internals foo
                            import: internal/mod
                            exposing: inc
                            :

                            defstruct: Pair a b
                            : first a
                            : second b

                            def: inc
                            : 1 +
                            """

                        expectedAst =
                            { moduleDefinition =
                                Defined
                                    { aliases =
                                        Dict.fromList
                                            [ ( "other", "/some/mod" )
                                            , ( "moar", "local/mod" )
                                            ]
                                    , imports =
                                        Dict.fromList
                                            [ ( "/some/other/mod", [ "test1", "word2" ] )
                                            , ( "internals", [ "foo" ] )
                                            , ( "internal/mod", [] )
                                            ]
                                    , exposes = Set.fromList [ "inc" ]
                                    }
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ CustomTypeDef
                                        emptyRange
                                        "Pair"
                                        [ "a", "b" ]
                                        [ ( "first", Generic "a" )
                                        , ( "second", Generic "b" )
                                        ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "inc"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    ]
                            }
                                |> addFunctionsForStructs
                    in
                    case compile source of
                        Err err ->
                            Expect.fail <| "Did not expect parsing to fail: " ++ Debug.toString err

                        Ok ast ->
                            Expect.equal expectedAst ast
            , test "Functions can have its own aliases and imports" <|
                \_ ->
                    let
                        source =
                            """
                            def: inc
                            alias: other /some/mod
                            alias: moar local/mod
                            import: /some/other/mod test1 word2
                            import: internals foo
                            import: internal/mod
                            : 1 +
                            """

                        expectedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "inc"
                                      , typeSignature = NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases =
                                            Dict.fromList
                                                [ ( "other", "/some/mod" )
                                                , ( "moar", "local/mod" )
                                                ]
                                      , imports =
                                            Dict.fromList
                                                [ ( "/some/other/mod", [ "test1", "word2" ] )
                                                , ( "internals", [ "foo" ] )
                                                , ( "internal/mod", [] )
                                                ]
                                      , implementation =
                                            SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    ]
                            }
                                |> addFunctionsForStructs
                    in
                    case compile source of
                        Err err ->
                            Expect.fail <| "Did not expect parsing to fail: " ++ Debug.toString err

                        Ok ast ->
                            Expect.equal expectedAst ast
            ]
        ]

Modified tests/Test/Parser/Util.elm from [d64d255e03] to [c6efc18281].

26
27
28
29
30
31
32

33
34
35
36
37
38
39
40
..
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
...
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146





147
148
149
150
151
152
153
154
155
156
157
158
159




160
161
162
163
164
165
166
167
168
169
170
171
172
173




174
175
176
177
178
179
180
compileRetainLocations str =
    String.unindent str
        |> run


stripLocations : AST -> AST
stripLocations ast =

    { types = Dict.map (\_ t -> stripTypeLocation t) ast.types
    , words = Dict.map (\_ d -> stripWordLocation d) ast.words
    }


stripTypeLocation : TypeDefinition -> TypeDefinition
stripTypeLocation typeDef =
    case typeDef of
................................................................................
            AST.UnionTypeDef emptyRange name generics members


stripWordLocation : WordDefinition -> WordDefinition
stripWordLocation word =
    { word
        | implementation = stripImplementationLocation word.implementation
        , metadata = Metadata.clearSourceLocationRange word.metadata
    }


stripImplementationLocation : WordImplementation -> WordImplementation
stripImplementationLocation impl =
    case impl of
        SoloImpl nodes ->
................................................................................

                _ ->
                    wipAst
    in
    Dict.foldl helper ast ast.types


addFunctionsForStructsHelper : String -> List String -> List ( String, Type ) -> AST -> AST
addFunctionsForStructsHelper name generics members ast =
    let
        selfType =
            if List.isEmpty generics then
                Type.Custom name

            else
                Type.CustomGeneric name (List.map Type.Generic generics)

        ctor =
            { name =
                if List.isEmpty members then
                    name

                else
                    ">" ++ name
            , metadata =
                Metadata.default
                    |> Metadata.withVerifiedType (List.map Tuple.second members) [ selfType ]





            , implementation = AST.SoloImpl [ AST.ConstructType name ]
            }

        setters =
            List.map settersHelper members

        settersHelper ( memberName, type_ ) =
            { name = ">" ++ memberName
            , metadata =
                Metadata.default
                    |> Metadata.withVerifiedType
                        [ selfType, type_ ]
                        [ selfType ]




            , implementation =
                AST.SoloImpl [ AST.SetMember name memberName ]
            }

        getters =
            List.map gettersHelper members

        gettersHelper ( memberName, type_ ) =
            { name = memberName ++ ">"
            , metadata =
                Metadata.default
                    |> Metadata.withVerifiedType
                        [ selfType ]
                        [ type_ ]




            , implementation =
                AST.SoloImpl [ AST.GetMember name memberName ]
            }

        allFuncs =
            (ctor :: setters)
                ++ getters







>
|







 







|







 







|



|
<
<
<
<








|
|
|
>
>
>
>
>








|
<
|
|
|
>
>
>
>









|
<
|
|
|
>
>
>
>







26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
..
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
...
121
122
123
124
125
126
127
128
129
130
131
132




133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

175
176
177
178
179
180
181
182
183
184
185
186
187
188
compileRetainLocations str =
    String.unindent str
        |> run


stripLocations : AST -> AST
stripLocations ast =
    { moduleDefinition = ast.moduleDefinition
    , types = Dict.map (\_ t -> stripTypeLocation t) ast.types
    , words = Dict.map (\_ d -> stripWordLocation d) ast.words
    }


stripTypeLocation : TypeDefinition -> TypeDefinition
stripTypeLocation typeDef =
    case typeDef of
................................................................................
            AST.UnionTypeDef emptyRange name generics members


stripWordLocation : WordDefinition -> WordDefinition
stripWordLocation word =
    { word
        | implementation = stripImplementationLocation word.implementation
        , sourceLocationRange = Nothing
    }


stripImplementationLocation : WordImplementation -> WordImplementation
stripImplementationLocation impl =
    case impl of
        SoloImpl nodes ->
................................................................................

                _ ->
                    wipAst
    in
    Dict.foldl helper ast ast.types


addFunctionsForStructsHelper : String -> List String -> List ( String, AST.PossiblyQualifiedType ) -> AST -> AST
addFunctionsForStructsHelper name generics members ast =
    let
        selfType =
            LocalRef name (List.map Generic generics)





        ctor =
            { name =
                if List.isEmpty members then
                    name

                else
                    ">" ++ name
            , typeSignature =
                Verified
                    { input = List.map Tuple.second members
                    , output = [ selfType ]
                    }
            , sourceLocationRange = Nothing
            , aliases = Dict.empty
            , imports = Dict.empty
            , implementation = AST.SoloImpl [ AST.ConstructType name ]
            }

        setters =
            List.map settersHelper members

        settersHelper ( memberName, type_ ) =
            { name = ">" ++ memberName
            , typeSignature =

                Verified
                    { input = [ selfType, type_ ]
                    , output = [ selfType ]
                    }
            , sourceLocationRange = Nothing
            , aliases = Dict.empty
            , imports = Dict.empty
            , implementation =
                AST.SoloImpl [ AST.SetMember name memberName ]
            }

        getters =
            List.map gettersHelper members

        gettersHelper ( memberName, type_ ) =
            { name = memberName ++ ">"
            , typeSignature =

                Verified
                    { input = [ selfType ]
                    , output = [ type_ ]
                    }
            , sourceLocationRange = Nothing
            , aliases = Dict.empty
            , imports = Dict.empty
            , implementation =
                AST.SoloImpl [ AST.GetMember name memberName ]
            }

        allFuncs =
            (ctor :: setters)
                ++ getters

Modified tests/Test/Qualifier.elm from [883b702e60] to [a69b471d1a].

5
6
7
8
9
10
11

12
13
14
15
16
17
18
19
20
21
22
23
24

25
26
27
28
29



30
31
32
33
34
35
36
37



38
39
40
41
42
43
44
45
46
47

48
49
50
51
52
53
54
..
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
..
96
97
98
99
100
101
102

103
104
105
106
107
108
109
110
111




112
113
114
115
116
117
118
...
143
144
145
146
147
148
149

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

180
181
182
183
184
185
186
187
188
189
190
191
192
193
...
202
203
204
205
206
207
208

209
210
211
212
213
214
215
216
217



218
219





220
221
222
223
224
225
226
227
228

229
230
231
232
233
234
235
...
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
...
298
299
300
301
302
303
304

305
306
307
308
309
310
311

312
313
314
315
316
317
318
319
320
321
322



323
324
325
326
327
328
329
...
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
...
365
366
367
368
369
370
371

372
373
374
375
376
377
378

379
380
381
382
383
384
385
...
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
...
437
438
439
440
441
442
443

444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478

479
480
481
482
483
484
485
486

487
488
489
490
491
492
493
...
503
504
505
506
507
508
509

510
511
512
513
514
515
516
517
518
519
520
521
522
523



524
525
526
527
528
529
530
531
532
533
...
535
536
537
538
539
540
541

542
543
544
545
546
547
548
549
550
551
552
553
554
...
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
...
653
654
655
656
657
658
659

660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684




685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705




706
707
708
709
710
711
712
713
714
715
716
717





718
719
720
721
722
723
724
...
731
732
733
734
735
736
737

738
739
740
741

742
743
744
745

746
747
748
749
750
751
752
...
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
....
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
1054
1055
1056
1057





1058
1059
1060
1061
1062
1063
1064
1065
1066








1067
1068
1069
1070
1071
1072



1073
1074
1075
1076
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
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193

1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
import Expect
import Play.Data.Builtin as Builtin
import Play.Data.Metadata as Metadata
import Play.Data.SourceLocation exposing (emptyRange)
import Play.Data.Type as Type
import Play.Parser as AST
import Play.Qualifier exposing (..)

import Set
import Test exposing (Test, describe, test)
import Test.Parser.Util as ParserUtil
import Test.Qualifier.Util as QualifierUtil


suite : Test
suite =
    describe "Qualifier"
        [ test "Simple program" <|
            \_ ->
                let
                    unqualifiedAst =

                        { types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "inc"
                                  , metadata = Metadata.default



                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "+"
                                            ]
                                  }
                                , { name = "dec"
                                  , metadata = Metadata.default



                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "-"
                                            ]
                                  }
                                , { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.asEntryPoint

                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "inc"
                                            , AST.Word emptyRange "inc"
                                            , AST.Word emptyRange "dec"
                                            , AST.Integer emptyRange 2
................................................................................
                                  , implementation =
                                        SoloImpl
                                            [ Integer emptyRange 1
                                            , Builtin emptyRange Builtin.Minus
                                            ]
                                  }
                                , { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.asEntryPoint
                                  , implementation =
                                        SoloImpl
                                            [ Integer emptyRange 1
                                            , Word emptyRange "inc"
                                            , Word emptyRange "inc"
                                            , Word emptyRange "dec"
                                            , Integer emptyRange 2
................................................................................
                        }
                in
                QualifierUtil.expectOutput unqualifiedAst expectedAst
        , test "Generic function types" <|
            \_ ->
                let
                    unqualifiedAst =

                        { types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "over"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType
                                                [ Type.Generic "a", Type.Generic "b" ]
                                                [ Type.Generic "a", Type.Generic "b", Type.Generic "a" ]




                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Word emptyRange "swap"
                                            , AST.Word emptyRange "dup"
                                            , AST.Word emptyRange "rotate"
                                            ]
                                  }
................................................................................
                        }
                in
                QualifierUtil.expectOutput unqualifiedAst expectedAst
        , test "Union types and multifunctions" <|
            \_ ->
                let
                    unqualifiedAst =

                        { types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ AST.UnionTypeDef emptyRange
                                    "Bool"
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , AST.CustomTypeDef emptyRange "True" [] []
                                , AST.CustomTypeDef emptyRange "False" [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "to-int"
                                  , metadata = Metadata.default



                                  , implementation =
                                        AST.MultiImpl
                                            [ ( AST.TypeMatch emptyRange (Type.Custom "False") [], [ AST.Integer emptyRange 0 ] )
                                            , ( AST.TypeMatch emptyRange (Type.Custom "True") [], [ AST.Integer emptyRange 1 ] )
                                            ]
                                            []
                                  }
                                ]
                        }
                            |> ParserUtil.addFunctionsForStructs

                    expectedAst =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef "Bool"

                                    emptyRange
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , CustomTypeDef "True" emptyRange [] []
                                , CustomTypeDef "False" emptyRange [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "to-int"
                                  , metadata = Metadata.default
                                  , implementation =
                                        MultiImpl
................................................................................
                in
                QualifierUtil.expectOutput unqualifiedAst expectedAst
        , describe "Quotations"
            [ test "Basic case" <|
                \_ ->
                    let
                        unqualifiedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "apply-to-num"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
                                                    [ Type.Int
                                                    , Type.Quotation { input = [ Type.Int ], output = [ Type.Int ] }



                                                    ]
                                                    [ Type.Int ]





                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Word emptyRange "!"
                                                ]
                                      }
                                    , { name = "main"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint

                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Quotation emptyRange
                                                    [ AST.Integer emptyRange 1
                                                    , AST.Word emptyRange "+"
                                                    ]
................................................................................
                                                    [ Type.Int ]
                                      , implementation =
                                            SoloImpl
                                                [ Builtin emptyRange Builtin.Apply
                                                ]
                                      }
                                    , { name = "main"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , WordRef emptyRange "quote:main/2"
                                                , Word emptyRange "apply-to-num"
                                                , WordRef emptyRange "quote:main/1"
                                                , Word emptyRange "apply-to-num"
................................................................................
                            }
                    in
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            , test "Quoting a word which hasn't been qualified yet is fine" <|
                \_ ->
                    let
                        unqualifiedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "a"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint

                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Quotation emptyRange
                                                    [ AST.Word emptyRange "inc"
                                                    ]
                                                , AST.Word emptyRange "!"
                                                ]
                                      }
                                    , { name = "inc"
                                      , metadata = Metadata.default



                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    ]
................................................................................
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "a"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , WordRef emptyRange "quote:a/1"
                                                , Builtin emptyRange Builtin.Apply
                                                ]
                                      }
................................................................................
                            }
                    in
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            , test "Quotes within quotes is fine" <|
                \_ ->
                    let
                        unqualifiedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "main"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint

                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Quotation emptyRange
                                                    [ AST.Integer emptyRange 1
                                                    , AST.Quotation emptyRange
                                                        [ AST.Integer emptyRange 1
................................................................................
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "main"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , WordRef emptyRange "quote:main/1"
                                                , Builtin emptyRange Builtin.Apply
                                                ]
                                      }
................................................................................
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            ]
        , describe "Pattern matching"
            [ test "Basic example" <|
                \_ ->
                    let
                        unqualifiedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ AST.UnionTypeDef emptyRange
                                        "Bool"
                                        []
                                        [ Type.Custom "True"
                                        , Type.Custom "False"
                                        ]
                                    , AST.CustomTypeDef emptyRange "True" [] []
                                    , AST.CustomTypeDef emptyRange "False" [] []
                                    , AST.CustomTypeDef emptyRange
                                        "Box"
                                        []
                                        [ ( "value", Type.Int ) ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "zero?"
                                      , metadata = Metadata.default



                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (Type.Custom "Box") [ ( "value", AST.LiteralInt 0 ) ]
                                                  , [ AST.Word emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "False" ]
                                      }
                                    ]
                            }
                                |> ParserUtil.addFunctionsForStructs

                        expectedAst =
                            { types =
                                Dict.fromListBy typeDefinitionName
                                    [ UnionTypeDef "Bool"

                                        emptyRange
                                        []
                                        [ Type.Custom "True"
                                        , Type.Custom "False"
                                        ]
                                    , CustomTypeDef "True" emptyRange [] []
                                    , CustomTypeDef "False" emptyRange [] []
                                    , CustomTypeDef "Box"

                                        emptyRange
                                        []
                                        [ ( "value", Type.Int ) ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "zero?"
................................................................................
                                |> QualifierUtil.addFunctionsForStructs
                    in
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            , test "Generic cases are allowed" <|
                \_ ->
                    let
                        unqualifiedAst =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ AST.UnionTypeDef emptyRange
                                        "Maybe"
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nothing"
                                        ]
                                    , AST.CustomTypeDef emptyRange "Nothing" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "with-default"
                                      , metadata = Metadata.default



                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (Type.Generic "a") []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "swap"
                                                , AST.Word emptyRange "drop"
                                                ]
                                      }
................................................................................
                            }
                                |> ParserUtil.addFunctionsForStructs

                        expectedAst =
                            { types =
                                Dict.fromListBy typeDefinitionName
                                    [ UnionTypeDef "Maybe"

                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nothing"
                                        ]
                                    , CustomTypeDef "Nothing" emptyRange [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "with-default"
                                      , metadata = Metadata.default
                                      , implementation =
                                            MultiImpl
................................................................................
                    boolUnion =
                        Type.Union
                            [ Type.Custom "True"
                            , Type.Custom "False"
                            ]

                    unqualifiedAst =

                        { types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ AST.UnionTypeDef emptyRange
                                    "Bool"
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , AST.CustomTypeDef emptyRange "True" [] []
                                , AST.CustomTypeDef emptyRange "False" [] []
                                , AST.CustomTypeDef emptyRange
                                    "Box"
                                    []
                                    [ ( "value", Type.Custom "Bool" ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "true?"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [ Type.Custom "Box" ] [ Type.Custom "Bool" ]





                                  , implementation =
                                        AST.MultiImpl
                                            [ ( AST.TypeMatch emptyRange
                                                    (Type.Custom "Box")
                                                    [ ( "value", AST.LiteralType (Type.Custom "True") ) ]
                                              , [ AST.Word emptyRange "True" ]
                                              )
                                            ]
                                            [ AST.Word emptyRange "False" ]
                                  }
                                ]
                        }
                            |> ParserUtil.addFunctionsForStructs

                    expectedAst =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef "Bool"

                                    emptyRange
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , CustomTypeDef "True" emptyRange [] []
                                , CustomTypeDef "False" emptyRange [] []
                                , CustomTypeDef "Box"

                                    emptyRange
                                    []
                                    [ ( "value", boolUnion ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "true?"
................................................................................
                let
                    qualifiedUsMoneyUnion =
                        [ Type.Custom "/play/test/some/module/Dollar"
                        , Type.Custom "/play/test/some/module/Cent"
                        ]

                    unqualifiedAst =

                        { types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ AST.UnionTypeDef emptyRange
                                    "USMoney"
                                    []
                                    [ Type.Custom "Dollar"
                                    , Type.Custom "Cent"
                                    ]
                                , AST.CustomTypeDef emptyRange
                                    "Dollar"
                                    []
                                    [ ( "dollar-value", Type.Int ) ]
                                , AST.CustomTypeDef emptyRange
                                    "Cent"
                                    []
                                    [ ( "cent-value", Type.Int ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "into-cents"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType
                                                [ Type.Custom "USMoney" ]
                                                [ Type.Custom "USMoney" ]




                                  , implementation =
                                        AST.MultiImpl
                                            [ ( AST.TypeMatch emptyRange (Type.Custom "Dollar") []
                                              , [ AST.Word emptyRange "dollar-value>"
                                                , AST.Integer emptyRange 100
                                                , AST.Word emptyRange "*"
                                                ]
                                              )
                                            , ( AST.TypeMatch emptyRange (Type.Custom "Cent") []
                                              , [ AST.Word emptyRange "cent-value>"
                                                ]
                                              )
                                            ]
                                            []
                                  }
                                , { name = "add-money"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType
                                                [ Type.Custom "USMoney", Type.Custom "USMoney" ]
                                                [ Type.Custom "USMoney" ]




                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Word emptyRange "into-cents"
                                            , AST.Word emptyRange "swap"
                                            , AST.Word emptyRange "into-cents"
                                            , AST.Word emptyRange "+"
                                            ]
                                  }
                                , { name = "quote-excuse"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [ Type.Custom "Dollar" ] [ Type.Custom "Dollar" ]





                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Word emptyRange "dollar-value>"
                                            , AST.Quotation emptyRange
                                                [ AST.Integer emptyRange 2
                                                , AST.Word emptyRange "*"
                                                ]
................................................................................
                            |> ParserUtil.addFunctionsForStructs

                    expectedAst =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef
                                    "/play/test/some/module/USMoney"

                                    emptyRange
                                    []
                                    qualifiedUsMoneyUnion
                                , CustomTypeDef "/play/test/some/module/Dollar"

                                    emptyRange
                                    []
                                    [ ( "dollar-value", Type.Int ) ]
                                , CustomTypeDef "/play/test/some/module/Cent"

                                    emptyRange
                                    []
                                    [ ( "cent-value", Type.Int ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "/play/test/some/module/into-cents"
................................................................................
                let
                    qualifiedUsMoneyUnion =
                        [ Type.Custom "/play/test/some/module/Dollar"
                        , Type.Custom "/play/test/some/module/Cent"
                        ]

                    unqualifiedAst =

                        { types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ AST.UnionTypeDef emptyRange
                                    "USMoney"
                                    []
                                    [ Type.Custom "Dollar"
                                    , Type.Custom "Cent"
                                    ]
                                , AST.CustomTypeDef emptyRange
                                    "Wallet"
                                    []
                                    [ ( "user-id", Type.Int )
                                    , ( "value", Type.Custom "USMoney" )
                                    ]
                                , AST.CustomTypeDef emptyRange
                                    "Dollar"
                                    []
                                    [ ( "dollar-value", Type.Int ) ]
                                , AST.CustomTypeDef emptyRange
                                    "Cent"
                                    []
                                    [ ( "cent-value", Type.Int ) ]
                                ]
                        , words = Dict.empty
                        }
                            |> ParserUtil.addFunctionsForStructs

                    expectedAst =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef
                                    "/play/test/some/module/USMoney"

                                    emptyRange
                                    []
                                    qualifiedUsMoneyUnion
                                , CustomTypeDef "/play/test/some/module/Dollar"

                                    emptyRange
                                    []
                                    [ ( "dollar-value", Type.Int ) ]
                                , CustomTypeDef "/play/test/some/module/Cent"

                                    emptyRange
                                    []
                                    [ ( "cent-value", Type.Int ) ]
                                , CustomTypeDef "/play/test/some/module/Wallet"

                                    emptyRange
                                    []
                                    [ ( "user-id", Type.Int )
                                    , ( "value", Type.Union qualifiedUsMoneyUnion )
                                    ]
                                ]
                        , words =
................................................................................
                                        SoloImpl
                                            [ GetMember "/play/test/some/module/Wallet" "value" ]
                                  }
                                ]
                        }
                in
                QualifierUtil.expectModuleOutput unqualifiedAst expectedAst
































































































































        , describe "Module loading"
            [ test "Detects package reference in simple word" <|


















































                \_ ->
                    let
                        unqualifiedAst =



















                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "call-external"
                                      , metadata = Metadata.default
                                      , implementation =





































































































                                            AST.SoloImpl



























































































































































































                                                [ AST.Integer emptyRange 1





























































































































































































































































































































                                                , AST.PackageWord emptyRange [ "package", "module" ] "sample"


















































































































































































































































































































































































































































































































































































































































                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { additionalModulesRequired =


































                                Set.fromList
                                    [ "/play/test/package/module" ]


                            , checkForExistingTypes = Set.empty
                            , checkForExistingWords =





















                                Set.fromList
                                    [ "/play/test/package/module/sample" ]





































                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "/play/test/package/tests/call-external"
                                      , metadata = Metadata.default





                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Word emptyRange "/play/test/package/module/sample"
                                                ]
                                      }
                                    ]
                            }









                        result =
                            run
                                { packageName = "play/test"
                                , modulePath = "package/tests"
                                , ast = unqualifiedAst
                                , externalModules = Dict.empty



                                }
                    in
                    case result of
                        Err err ->
                            Expect.fail <| "Did not expect qualification to fail with error: " ++ Debug.toString err


                        Ok actualAst ->
                            Expect.equal expectedAst actualAst
            , test "Detects external reference in simple word" <|






                \_ ->
                    let
                        unqualifiedAst =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "call-external"
                                      , metadata = Metadata.default








                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.ExternalWord emptyRange [ "package", "module" ] "sample" ]


                                      }
                                    ]
                            }































                        expectedAst =


























                            { additionalModulesRequired =
                                Set.fromList
                                    [ "/external/test/package/module" ]
                            , checkForExistingTypes = Set.empty
                            , checkForExistingWords =




















































                                Set.fromList
                                    [ "/external/test/package/module/sample"







                                    ]










                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "/play/test/package/tests/call-external"
                                      , metadata = Metadata.default









                                      , implementation =
                                            SoloImpl
                                                [ Word emptyRange "/external/test/package/module/sample" ]

                                      }
                                    ]
                            }








                        result =
                            run
                                { packageName = "play/test"
                                , modulePath = "package/tests"






























































































































































































                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList
                                        [ ( "/package/module", "external/test" )
                                        ]
                                }
                    in
                    case result of
                        Err err ->
                            Expect.fail <| "Did not expect qualification to fail with error: " ++ Debug.toString err

                        Ok actualAst ->
                            Expect.equal expectedAst actualAst
            , test "Detects package reference in multiword" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "call-external"
                                      , metadata = Metadata.default
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange Type.Int [ ( "value", AST.LiteralInt 1 ) ]
                                                  , [ AST.PackageWord emptyRange [ "package", "module" ] "when-one"
                                                    ]
                                                  )
                                                ]
                                                [ AST.PackageWord emptyRange [ "package", "module" ] "when-other-one" ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { additionalModulesRequired =
                                Set.fromList
                                    [ "/play/test/package/module" ]
                            , checkForExistingTypes = Set.empty
                            , checkForExistingWords =
                                Set.fromList
                                    [ "/play/test/package/module/when-one"
                                    , "/play/test/package/module/when-other-one"
                                    ]
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "/play/test/package/tests/call-external"
                                      , metadata = Metadata.default
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange Type.Int [ ( "value", LiteralInt 1 ) ]
                                                  , [ Word emptyRange "/play/test/package/module/when-one"
                                                    ]
                                                  )
                                                ]
                                                [ Word emptyRange "/play/test/package/module/when-other-one" ]
                                      }
                                    ]
                            }

                        result =
                            run
                                { packageName = "play/test"
                                , modulePath = "package/tests"
                                , ast = unqualifiedAst
                                , externalModules = Dict.empty
                                }
                    in
                    case result of
                        Err err ->
                            Expect.fail <| "Did not expect qualification to fail with error: " ++ Debug.toString err


                        Ok actualAst ->
                            Expect.equal expectedAst actualAst
            , test "Detects external reference in multiword" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "call-external"
                                      , metadata = Metadata.default
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange Type.Int [ ( "value", AST.LiteralInt 1 ) ]
                                                  , [ AST.ExternalWord emptyRange [ "package", "module" ] "when-one"
                                                    ]
                                                  )
                                                ]
                                                [ AST.ExternalWord emptyRange [ "package", "module" ] "when-other-one" ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { additionalModulesRequired =
                                Set.fromList
                                    [ "/external/test/package/module" ]
                            , checkForExistingTypes = Set.empty
                            , checkForExistingWords =
                                Set.fromList
                                    [ "/external/test/package/module/when-one"
                                    , "/external/test/package/module/when-other-one"
                                    ]
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "/play/test/package/tests/call-external"
                                      , metadata = Metadata.default
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange Type.Int [ ( "value", LiteralInt 1 ) ]
                                                  , [ Word emptyRange "/external/test/package/module/when-one"
                                                    ]
                                                  )
                                                ]
                                                [ Word emptyRange "/external/test/package/module/when-other-one" ]
                                      }
                                    ]
                            }

                        result =
                            run
                                { packageName = "play/test"
                                , modulePath = "package/tests"
                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList
                                        [ ( "/package/module", "external/test" )
                                        ]
                                }
                    in
                    case result of
                        Err err ->
                            Expect.fail <| "Did not expect qualification to fail with error: " ++ Debug.toString err

                        Ok actualAst ->
                            Expect.equal expectedAst actualAst
            ]
        ]







>













>
|



|
>
>
>







|
>
>
>







|
|
|
>







 







<
|
<







 







>
|



|
|
|
|
<
>
>
>
>







 







>
|




|
|







|
>
>
>


|
|











>





|
|







 







>
|



|
|
|
|
|
>
>
>

<
>
>
>
>
>






|
|
|
>







 







<
|
<







 







>
|



|
|
|
>










|
>
>
>







 







<
|
<







 







>
|



|
|
|
>







 







<
|
<







 







>
|




|
|






|




|
>
>
>


|













>





|
|

>







 







>
|




|
|






|
>
>
>


|







 







>





|







 







>
|




|
|






|




|
|
|
>
>
>
>
>



|
|













>





|
|

>







 







>
|




|
|




|



|




|
|
|
|
<
>
>
>
>


|





|







|
|
|
|
<
>
>
>
>









|
|
|
>
>
>
>
>







 







>




>




>







 







>
|




|
|




|
|




|



|










>




>




>




>







 







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



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



|


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

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

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






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



<
<
>
>
>
>
>

|
|
|





>
>
>
>
>
>
>
>


|
|

|
>
>
>



|
<
>

<
<
<
>
>
>
>
>
>



>
|


|
<
>
>
>
>
>
>
>
>


<
>
>




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



<
<
>
>
>
>
>
>
>
>
>

|
|
>




>
>
>
>
>
>
>


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



|
|



<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
84
85
86
87
88
89
90

91

92
93
94
95
96
97
98
...
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

119
120
121
122
123
124
125
126
127
128
129
...
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
...
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238

239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
...
283
284
285
286
287
288
289

290

291
292
293
294
295
296
297
...
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
...
358
359
360
361
362
363
364

365

366
367
368
369
370
371
372
...
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
...
423
424
425
426
427
428
429

430

431
432
433
434
435
436
437
...
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
...
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
...
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
...
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
...
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729

730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753

754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
...
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
...
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
....
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
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219

1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
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
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573

2574
2575
2576

2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598

2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638


2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673

2674
2675



2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689

2690
2691
2692
2693
2694
2695
2696
2697
2698
2699

2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764



2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817

2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838


2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064






3065



















3066








3067


























3068

3069
3070















3071





















































import Expect
import Play.Data.Builtin as Builtin
import Play.Data.Metadata as Metadata
import Play.Data.SourceLocation exposing (emptyRange)
import Play.Data.Type as Type
import Play.Parser as AST
import Play.Qualifier exposing (..)
import Play.Qualifier.Problem as Problem
import Set
import Test exposing (Test, describe, test)
import Test.Parser.Util as ParserUtil
import Test.Qualifier.Util as QualifierUtil


suite : Test
suite =
    describe "Qualifier"
        [ test "Simple program" <|
            \_ ->
                let
                    unqualifiedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "inc"
                                  , typeSignature = AST.NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "+"
                                            ]
                                  }
                                , { name = "dec"
                                  , typeSignature = AST.NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "-"
                                            ]
                                  }
                                , { name = "main"
                                  , typeSignature = AST.NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Integer emptyRange 1
                                            , AST.Word emptyRange "inc"
                                            , AST.Word emptyRange "inc"
                                            , AST.Word emptyRange "dec"
                                            , AST.Integer emptyRange 2
................................................................................
                                  , implementation =
                                        SoloImpl
                                            [ Integer emptyRange 1
                                            , Builtin emptyRange Builtin.Minus
                                            ]
                                  }
                                , { name = "main"

                                  , metadata = Metadata.default

                                  , implementation =
                                        SoloImpl
                                            [ Integer emptyRange 1
                                            , Word emptyRange "inc"
                                            , Word emptyRange "inc"
                                            , Word emptyRange "dec"
                                            , Integer emptyRange 2
................................................................................
                        }
                in
                QualifierUtil.expectOutput unqualifiedAst expectedAst
        , test "Generic function types" <|
            \_ ->
                let
                    unqualifiedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "over"
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.Generic "a", AST.Generic "b" ]
                                            , output = [ AST.Generic "a", AST.Generic "b", AST.Generic "a" ]

                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Word emptyRange "swap"
                                            , AST.Word emptyRange "dup"
                                            , AST.Word emptyRange "rotate"
                                            ]
                                  }
................................................................................
                        }
                in
                QualifierUtil.expectOutput unqualifiedAst expectedAst
        , test "Union types and multifunctions" <|
            \_ ->
                let
                    unqualifiedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ AST.UnionTypeDef emptyRange
                                    "Bool"
                                    []
                                    [ AST.LocalRef "True" []
                                    , AST.LocalRef "False" []
                                    ]
                                , AST.CustomTypeDef emptyRange "True" [] []
                                , AST.CustomTypeDef emptyRange "False" [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "to-int"
                                  , typeSignature = AST.NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.MultiImpl
                                            [ ( AST.TypeMatch emptyRange (AST.LocalRef "False" []) [], [ AST.Integer emptyRange 0 ] )
                                            , ( AST.TypeMatch emptyRange (AST.LocalRef "True" []) [], [ AST.Integer emptyRange 1 ] )
                                            ]
                                            []
                                  }
                                ]
                        }
                            |> ParserUtil.addFunctionsForStructs

                    expectedAst =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef "Bool"
                                    True
                                    emptyRange
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , CustomTypeDef "True" True emptyRange [] []
                                , CustomTypeDef "False" True emptyRange [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "to-int"
                                  , metadata = Metadata.default
                                  , implementation =
                                        MultiImpl
................................................................................
                in
                QualifierUtil.expectOutput unqualifiedAst expectedAst
        , describe "Quotations"
            [ test "Basic case" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "apply-to-num"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input =
                                                    [ AST.LocalRef "Int" []
                                                    , AST.QuotationType
                                                        { input = [ AST.LocalRef "Int" [] ]
                                                        , output = [ AST.LocalRef "Int" [] ]
                                                        }
                                                    ]

                                                , output = [ AST.LocalRef "Int" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Word emptyRange "!"
                                                ]
                                      }
                                    , { name = "main"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Quotation emptyRange
                                                    [ AST.Integer emptyRange 1
                                                    , AST.Word emptyRange "+"
                                                    ]
................................................................................
                                                    [ Type.Int ]
                                      , implementation =
                                            SoloImpl
                                                [ Builtin emptyRange Builtin.Apply
                                                ]
                                      }
                                    , { name = "main"

                                      , metadata = Metadata.default

                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , WordRef emptyRange "quote:main/2"
                                                , Word emptyRange "apply-to-num"
                                                , WordRef emptyRange "quote:main/1"
                                                , Word emptyRange "apply-to-num"
................................................................................
                            }
                    in
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            , test "Quoting a word which hasn't been qualified yet is fine" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "a"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Quotation emptyRange
                                                    [ AST.Word emptyRange "inc"
                                                    ]
                                                , AST.Word emptyRange "!"
                                                ]
                                      }
                                    , { name = "inc"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    ]
................................................................................
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "a"

                                      , metadata = Metadata.default

                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , WordRef emptyRange "quote:a/1"
                                                , Builtin emptyRange Builtin.Apply
                                                ]
                                      }
................................................................................
                            }
                    in
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            , test "Quotes within quotes is fine" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "main"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Quotation emptyRange
                                                    [ AST.Integer emptyRange 1
                                                    , AST.Quotation emptyRange
                                                        [ AST.Integer emptyRange 1
................................................................................
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "main"

                                      , metadata = Metadata.default

                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , WordRef emptyRange "quote:main/1"
                                                , Builtin emptyRange Builtin.Apply
                                                ]
                                      }
................................................................................
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            ]
        , describe "Pattern matching"
            [ test "Basic example" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ AST.UnionTypeDef emptyRange
                                        "Bool"
                                        []
                                        [ AST.LocalRef "True" []
                                        , AST.LocalRef "False" []
                                        ]
                                    , AST.CustomTypeDef emptyRange "True" [] []
                                    , AST.CustomTypeDef emptyRange "False" [] []
                                    , AST.CustomTypeDef emptyRange
                                        "Box"
                                        []
                                        [ ( "value", AST.LocalRef "Int" [] ) ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "zero?"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.LocalRef "Box" []) [ ( "value", AST.LiteralInt 0 ) ]
                                                  , [ AST.Word emptyRange "True" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "False" ]
                                      }
                                    ]
                            }
                                |> ParserUtil.addFunctionsForStructs

                        expectedAst =
                            { types =
                                Dict.fromListBy typeDefinitionName
                                    [ UnionTypeDef "Bool"
                                        True
                                        emptyRange
                                        []
                                        [ Type.Custom "True"
                                        , Type.Custom "False"
                                        ]
                                    , CustomTypeDef "True" True emptyRange [] []
                                    , CustomTypeDef "False" True emptyRange [] []
                                    , CustomTypeDef "Box"
                                        True
                                        emptyRange
                                        []
                                        [ ( "value", Type.Int ) ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "zero?"
................................................................................
                                |> QualifierUtil.addFunctionsForStructs
                    in
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            , test "Generic cases are allowed" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ AST.UnionTypeDef emptyRange
                                        "Maybe"
                                        [ "a" ]
                                        [ AST.Generic "a"
                                        , AST.LocalRef "Nothing" []
                                        ]
                                    , AST.CustomTypeDef emptyRange "Nothing" [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "with-default"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.Generic "a") []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "swap"
                                                , AST.Word emptyRange "drop"
                                                ]
                                      }
................................................................................
                            }
                                |> ParserUtil.addFunctionsForStructs

                        expectedAst =
                            { types =
                                Dict.fromListBy typeDefinitionName
                                    [ UnionTypeDef "Maybe"
                                        True
                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nothing"
                                        ]
                                    , CustomTypeDef "Nothing" True emptyRange [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "with-default"
                                      , metadata = Metadata.default
                                      , implementation =
                                            MultiImpl
................................................................................
                    boolUnion =
                        Type.Union
                            [ Type.Custom "True"
                            , Type.Custom "False"
                            ]

                    unqualifiedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ AST.UnionTypeDef emptyRange
                                    "Bool"
                                    []
                                    [ AST.LocalRef "True" []
                                    , AST.LocalRef "False" []
                                    ]
                                , AST.CustomTypeDef emptyRange "True" [] []
                                , AST.CustomTypeDef emptyRange "False" [] []
                                , AST.CustomTypeDef emptyRange
                                    "Box"
                                    []
                                    [ ( "value", AST.LocalRef "Bool" [] ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "true?"
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.LocalRef "Box" [] ]
                                            , output = [ AST.LocalRef "Bool" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.MultiImpl
                                            [ ( AST.TypeMatch emptyRange
                                                    (AST.LocalRef "Box" [])
                                                    [ ( "value", AST.LiteralType (AST.LocalRef "True" []) ) ]
                                              , [ AST.Word emptyRange "True" ]
                                              )
                                            ]
                                            [ AST.Word emptyRange "False" ]
                                  }
                                ]
                        }
                            |> ParserUtil.addFunctionsForStructs

                    expectedAst =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef "Bool"
                                    True
                                    emptyRange
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , CustomTypeDef "True" True emptyRange [] []
                                , CustomTypeDef "False" True emptyRange [] []
                                , CustomTypeDef "Box"
                                    True
                                    emptyRange
                                    []
                                    [ ( "value", boolUnion ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "true?"
................................................................................
                let
                    qualifiedUsMoneyUnion =
                        [ Type.Custom "/play/test/some/module/Dollar"
                        , Type.Custom "/play/test/some/module/Cent"
                        ]

                    unqualifiedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ AST.UnionTypeDef emptyRange
                                    "USMoney"
                                    []
                                    [ AST.LocalRef "Dollar" []
                                    , AST.LocalRef "Cent" []
                                    ]
                                , AST.CustomTypeDef emptyRange
                                    "Dollar"
                                    []
                                    [ ( "dollar-value", AST.LocalRef "Int" [] ) ]
                                , AST.CustomTypeDef emptyRange
                                    "Cent"
                                    []
                                    [ ( "cent-value", AST.LocalRef "Int" [] ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "into-cents"
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.LocalRef "USMoney" [] ]
                                            , output = [ AST.LocalRef "USMoney" [] ]

                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.MultiImpl
                                            [ ( AST.TypeMatch emptyRange (AST.LocalRef "Dollar" []) []
                                              , [ AST.Word emptyRange "dollar-value>"
                                                , AST.Integer emptyRange 100
                                                , AST.Word emptyRange "*"
                                                ]
                                              )
                                            , ( AST.TypeMatch emptyRange (AST.LocalRef "Cent" []) []
                                              , [ AST.Word emptyRange "cent-value>"
                                                ]
                                              )
                                            ]
                                            []
                                  }
                                , { name = "add-money"
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.LocalRef "USMoney" [], AST.LocalRef "USMoney" [] ]
                                            , output = [ AST.LocalRef "USMoney" [] ]

                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Word emptyRange "into-cents"
                                            , AST.Word emptyRange "swap"
                                            , AST.Word emptyRange "into-cents"
                                            , AST.Word emptyRange "+"
                                            ]
                                  }
                                , { name = "quote-excuse"
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.LocalRef "Dollar" [] ]
                                            , output = [ AST.LocalRef "Dollar" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.Word emptyRange "dollar-value>"
                                            , AST.Quotation emptyRange
                                                [ AST.Integer emptyRange 2
                                                , AST.Word emptyRange "*"
                                                ]
................................................................................
                            |> ParserUtil.addFunctionsForStructs

                    expectedAst =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef
                                    "/play/test/some/module/USMoney"
                                    True
                                    emptyRange
                                    []
                                    qualifiedUsMoneyUnion
                                , CustomTypeDef "/play/test/some/module/Dollar"
                                    True
                                    emptyRange
                                    []
                                    [ ( "dollar-value", Type.Int ) ]
                                , CustomTypeDef "/play/test/some/module/Cent"
                                    True
                                    emptyRange
                                    []
                                    [ ( "cent-value", Type.Int ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "/play/test/some/module/into-cents"
................................................................................
                let
                    qualifiedUsMoneyUnion =
                        [ Type.Custom "/play/test/some/module/Dollar"
                        , Type.Custom "/play/test/some/module/Cent"
                        ]

                    unqualifiedAst =
                        { moduleDefinition = AST.emptyModuleDefinition
                        , types =
                            Dict.fromListBy AST.typeDefinitionName
                                [ AST.UnionTypeDef emptyRange
                                    "USMoney"
                                    []
                                    [ AST.LocalRef "Dollar" []
                                    , AST.LocalRef "Cent" []
                                    ]
                                , AST.CustomTypeDef emptyRange
                                    "Wallet"
                                    []
                                    [ ( "user-id", AST.LocalRef "Int" [] )
                                    , ( "value", AST.LocalRef "USMoney" [] )
                                    ]
                                , AST.CustomTypeDef emptyRange
                                    "Dollar"
                                    []
                                    [ ( "dollar-value", AST.LocalRef "Int" [] ) ]
                                , AST.CustomTypeDef emptyRange
                                    "Cent"
                                    []
                                    [ ( "cent-value", AST.LocalRef "Int" [] ) ]
                                ]
                        , words = Dict.empty
                        }
                            |> ParserUtil.addFunctionsForStructs

                    expectedAst =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef
                                    "/play/test/some/module/USMoney"
                                    True
                                    emptyRange
                                    []
                                    qualifiedUsMoneyUnion
                                , CustomTypeDef "/play/test/some/module/Dollar"
                                    True
                                    emptyRange
                                    []
                                    [ ( "dollar-value", Type.Int ) ]
                                , CustomTypeDef "/play/test/some/module/Cent"
                                    True
                                    emptyRange
                                    []
                                    [ ( "cent-value", Type.Int ) ]
                                , CustomTypeDef "/play/test/some/module/Wallet"
                                    True
                                    emptyRange
                                    []
                                    [ ( "user-id", Type.Int )
                                    , ( "value", Type.Union qualifiedUsMoneyUnion )
                                    ]
                                ]
                        , words =
................................................................................
                                        SoloImpl
                                            [ GetMember "/play/test/some/module/Wallet" "value" ]
                                  }
                                ]
                        }
                in
                QualifierUtil.expectModuleOutput unqualifiedAst expectedAst
        , test "Retrieve dependant modules" <|
            \_ ->
                let
                    unqualifiedAst =
                        { moduleDefinition =
                            AST.Defined
                                { aliases =
                                    Dict.fromList
                                        [ ( "html", "/external/html" ) ]
                                , imports =
                                    Dict.fromList
                                        [ ( "/external/module", [] ) ]
                                , exposes = Set.fromList []
                                }
                        , types =
                            Dict.fromList
                                [ ( "Tipe"
                                  , AST.CustomTypeDef emptyRange
                                        "Tipe"
                                        []
                                        [ ( "value", AST.ExternalRef [ "external", "double" ] "Tipe" [] ) ]
                                  )
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "call-external"
                                  , typeSignature =
                                        AST.UserProvided
                                            { input = [ AST.InternalRef [ "internal", "types" ] "In" [] ]
                                            , output = [ AST.ExternalRef [ "external", "types" ] "Out" [] ]
                                            }
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.MultiImpl
                                            [ ( AST.TypeMatch emptyRange (AST.LocalRef "Int" []) [ ( "value", AST.LiteralInt 1 ) ]
                                              , [ AST.PackageWord emptyRange [ "package", "module" ] "when-one"
                                                ]
                                              )
                                            , ( AST.TypeMatch emptyRange (AST.InternalRef [ "internal", "match" ] "Some" []) []
                                              , [ AST.Word emptyRange "drop" ]
                                              )
                                            ]
                                            [ AST.PackageWord emptyRange [ "package", "module" ] "when-other-one" ]
                                  }
                                , { name = "main"
                                  , typeSignature = AST.NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.fromList [ ( "ali", "internal/alias" ) ]
                                  , imports = Dict.fromList [ ( "/list/of/names", [ "one" ] ) ]
                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.PackageWord emptyRange [ "html" ] "div"
                                            , AST.Word emptyRange "call-external"
                                            , AST.ExternalWord emptyRange [ "some", "ext" ] "word"
                                            , AST.PackageWord emptyRange [ "ali" ] "word1"
                                            ]
                                  }
                                ]
                        }

                    expectedRequiredModules =
                        Set.fromList
                            [ "/robheghan/dummy/list/of/names"
                            , "/robheghan/dummy/some/ext"
                            , "/robheghan/html/external/html"
                            , "/robheghan/html/external/module"
                            , "/robheghan/html/external/types"
                            , "/robheghan/html/external/double"
                            , "/package/test/internal/alias"
                            , "/package/test/internal/types"
                            , "/package/test/internal/match"
                            , "/package/test/package/module"
                            , "/play/standard_library/core"
                            ]

                    actualRequiredModules =
                        requiredModules
                            { packageName = "package/test"
                            , ast = unqualifiedAst
                            , externalModules =
                                Dict.fromList
                                    [ ( "/list/of/names", "robheghan/dummy" )
                                    , ( "/some/ext", "robheghan/dummy" )
                                    , ( "/external/html", "robheghan/html" )
                                    , ( "/external/module", "robheghan/html" )
                                    , ( "/external/types", "robheghan/html" )
                                    , ( "/external/double", "robheghan/html" )
                                    , ( "/core", "play/standard_library" )
                                    ]
                            }
                in
                Expect.equal expectedRequiredModules actualRequiredModules
        , test "Reliance on standard_library/core only when standard_library is specified as externalModule" <|
            \_ ->
                let
                    unqualifiedAst =
                        { moduleDefinition = AST.Undefined
                        , types = Dict.empty
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
                                  , typeSignature = AST.NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.fromList [ ( "ali", "internal/alias" ) ]
                                  , imports = Dict.empty
                                  , implementation =
                                        AST.SoloImpl
                                            [ AST.PackageWord emptyRange [ "ali" ] "word1"
                                            ]
                                  }
                                ]
                        }

                    expectedRequiredModules =
                        Set.fromList
                            [ "/package/test/internal/alias"
                            ]

                    actualRequiredModules =
                        requiredModules
                            { packageName = "package/test"
                            , ast = unqualifiedAst
                            , externalModules = Dict.empty
                            }
                in
                Expect.equal expectedRequiredModules actualRequiredModules
        , describe "Module resolution" <|

            let
                dummyWord name =
                    dummyWordImpl name True

                dummyWordUnexposed name =
                    dummyWordImpl name False

                dummyWordImpl name isExposed =
                    ( name
                    , { name = name
                      , metadata =
                            Metadata.default
                                |> Metadata.isExposed isExposed
                      , implementation =
                            SoloImpl []
                      }
                    )

                dummyType name =
                    dummyTypeImpl name True

                dummyTypeUnexposed name =
                    dummyTypeImpl name False

                dummyTypeImpl name isExposed =
                    let
                        genericName =
                            name ++ "Generic"

                        unionName =
                            name ++ "Union"
                    in
                    [ ( name
                      , CustomTypeDef name isExposed emptyRange [] []
                      )
                    , ( genericName
                      , CustomTypeDef genericName isExposed emptyRange [ "a" ] []
                      )
                    , ( unionName
                      , UnionTypeDef unionName
                            isExposed
                            emptyRange
                            []
                            [ Type.Custom name
                            , Type.CustomGeneric genericName [ Type.Generic "a" ]
                            ]
                      )
                    ]
            in
            [ test "Qualifies word in internal package" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.PackageWord emptyRange [ "internal" ] "add"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata = Metadata.default
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Word emptyRange "internal/add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromList
                                    [ dummyWord "internal/add" ]
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies word in internal package (multiword)" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.LocalRef "Int" []) []
                                                  , [ AST.Integer emptyRange 0
                                                    , AST.PackageWord emptyRange [ "mod" ] "add"
                                                    ]
                                                  )
                                                ]
                                                [ AST.Integer emptyRange 1
                                                , AST.PackageWord emptyRange [ "mod" ] "add"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata = Metadata.default
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange Type.Int []
                                                  , [ Integer emptyRange 0
                                                    , Word emptyRange "mod/add"
                                                    ]
                                                  )
                                                ]
                                                [ Integer emptyRange 1
                                                , Word emptyRange "mod/add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromList
                                    [ dummyWord "mod/add" ]
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies type in internal package" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input =
                                                    [ AST.InternalRef [ "mod" ] "Tipe" []
                                                    , AST.InternalRef [ "mod" ] "TipeGeneric" [ AST.Generic "a" ]
                                                    , AST.InternalRef [ "mod" ] "TipeUnion" []
                                                    ]
                                                , output = []
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Word emptyRange "drop"
                                                , AST.Word emptyRange "drop"
                                                , AST.Word emptyRange "drop"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
                                                    [ Type.Custom "mod/Tipe"
                                                    , Type.CustomGeneric "mod/TipeGeneric" [ Type.Generic "a" ]
                                                    , Type.Union
                                                        [ Type.Custom "mod/Tipe"
                                                        , Type.CustomGeneric "mod/TipeGeneric" [ Type.Generic "a" ]
                                                        ]
                                                    ]
                                                    []
                                      , implementation =
                                            SoloImpl
                                                [ Builtin emptyRange Builtin.StackDrop
                                                , Builtin emptyRange Builtin.StackDrop
                                                , Builtin emptyRange Builtin.StackDrop
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "mod/Tipe" ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies type in internal package (multiword)" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.InternalRef [ "mod" ] "TipeUnion" [] ]
                                                , output = []
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.InternalRef [ "mod" ] "Tipe" []) []
                                                  , [ AST.Word emptyRange "drop"
                                                    , AST.Word emptyRange "drop"
                                                    ]
                                                  )
                                                , ( AST.TypeMatch emptyRange (AST.InternalRef [ "mod" ] "TipeGeneric" [ AST.Generic "a" ]) []
                                                  , [ AST.Word emptyRange "drop"
                                                    , AST.Word emptyRange "drop"
                                                    ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "drop"
                                                , AST.Word emptyRange "drop"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
                                                    [ Type.Union
                                                        [ Type.Custom "mod/Tipe"
                                                        , Type.CustomGeneric "mod/TipeGeneric" [ Type.Generic "a" ]
                                                        ]
                                                    ]
                                                    []
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Type.Custom "mod/Tipe") []
                                                  , [ Builtin emptyRange Builtin.StackDrop
                                                    , Builtin emptyRange Builtin.StackDrop
                                                    ]
                                                  )
                                                , ( TypeMatch emptyRange (Type.CustomGeneric "mod/TipeGeneric" [ Type.Generic "a" ]) []
                                                  , [ Builtin emptyRange Builtin.StackDrop
                                                    , Builtin emptyRange Builtin.StackDrop
                                                    ]
                                                  )
                                                ]
                                                [ Builtin emptyRange Builtin.StackDrop
                                                , Builtin emptyRange Builtin.StackDrop
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "mod/Tipe" ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies member type in internal package" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromList
                                    [ ( "SomeType"
                                      , AST.CustomTypeDef emptyRange
                                            "SomeType"
                                            []
                                            [ ( "tipe", AST.InternalRef [ "mod" ] "Tipe" [] ) ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        expectedAst =
                            { types =
                                Dict.fromList
                                    [ ( "SomeType"
                                      , CustomTypeDef "SomeType"
                                            True
                                            emptyRange
                                            []
                                            [ ( "tipe", Type.Custom "mod/Tipe" ) ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "mod/Tipe" ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies word in external package" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.ExternalWord emptyRange [ "mod" ] "add"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata = Metadata.default
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Word emptyRange "/external/package/mod/add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromList
                                    [ dummyWord "/external/package/mod/add" ]
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies word in external package (multiword)" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.LocalRef "Int" []) []
                                                  , [ AST.Integer emptyRange 0
                                                    , AST.ExternalWord emptyRange [ "mod" ] "add"
                                                    ]
                                                  )
                                                ]
                                                [ AST.Integer emptyRange 1
                                                , AST.ExternalWord emptyRange [ "mod" ] "add"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata = Metadata.default
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange Type.Int []
                                                  , [ Integer emptyRange 0
                                                    , Word emptyRange "/external/package/mod/add"
                                                    ]
                                                  )
                                                ]
                                                [ Integer emptyRange 1
                                                , Word emptyRange "/external/package/mod/add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromList
                                    [ dummyWord "/external/package/mod/add" ]
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies type in external package" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input =
                                                    [ AST.ExternalRef [ "mod" ] "Tipe" []
                                                    , AST.ExternalRef [ "mod" ] "TipeGeneric" [ AST.Generic "a" ]
                                                    , AST.ExternalRef [ "mod" ] "TipeUnion" []
                                                    ]
                                                , output = []
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Word emptyRange "drop"
                                                , AST.Word emptyRange "drop"
                                                , AST.Word emptyRange "drop"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
                                                    [ Type.Custom "/external/package/mod/Tipe"
                                                    , Type.CustomGeneric "/external/package/mod/TipeGeneric" [ Type.Generic "a" ]
                                                    , Type.Union
                                                        [ Type.Custom "/external/package/mod/Tipe"
                                                        , Type.CustomGeneric "/external/package/mod/TipeGeneric" [ Type.Generic "a" ]
                                                        ]
                                                    ]
                                                    []
                                      , implementation =
                                            SoloImpl
                                                [ Builtin emptyRange Builtin.StackDrop
                                                , Builtin emptyRange Builtin.StackDrop
                                                , Builtin emptyRange Builtin.StackDrop
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe" ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies type in external package (multiword)" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.ExternalRef [ "mod" ] "TipeUnion" [] ]
                                                , output = []
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.ExternalRef [ "mod" ] "Tipe" []) []
                                                  , [ AST.Word emptyRange "drop"
                                                    , AST.Word emptyRange "drop"
                                                    ]
                                                  )
                                                , ( AST.TypeMatch emptyRange (AST.ExternalRef [ "mod" ] "TipeGeneric" [ AST.Generic "a" ]) []
                                                  , [ AST.Word emptyRange "drop"
                                                    , AST.Word emptyRange "drop"
                                                    ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "drop"
                                                , AST.Word emptyRange "drop"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
                                                    [ Type.Union
                                                        [ Type.Custom "/external/package/mod/Tipe"
                                                        , Type.CustomGeneric "/external/package/mod/TipeGeneric" [ Type.Generic "a" ]
                                                        ]
                                                    ]
                                                    []
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Type.Custom "/external/package/mod/Tipe") []
                                                  , [ Builtin emptyRange Builtin.StackDrop
                                                    , Builtin emptyRange Builtin.StackDrop
                                                    ]
                                                  )
                                                , ( TypeMatch emptyRange (Type.CustomGeneric "/external/package/mod/TipeGeneric" [ Type.Generic "a" ]) []
                                                  , [ Builtin emptyRange Builtin.StackDrop
                                                    , Builtin emptyRange Builtin.StackDrop
                                                    ]
                                                  )
                                                ]
                                                [ Builtin emptyRange Builtin.StackDrop
                                                , Builtin emptyRange Builtin.StackDrop
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe" ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Qualifies member type in external package" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromList
                                    [ ( "SomeType"
                                      , AST.CustomTypeDef emptyRange
                                            "SomeType"
                                            []
                                            [ ( "tipe", AST.ExternalRef [ "mod" ] "Tipe" [] ) ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        expectedAst =
                            { types =
                                Dict.fromList
                                    [ ( "SomeType"
                                      , CustomTypeDef "SomeType"
                                            True
                                            emptyRange
                                            []
                                            [ ( "tipe", Type.Custom "/external/package/mod/Tipe" ) ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe" ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Module alias" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases =
                                        Dict.fromList
                                            [ ( "ext", "/mod" )
                                            , ( "internal", "internal/mod" )
                                            ]
                                    , imports = Dict.empty
                                    , exposes = Set.empty
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.InternalRef [ "ext" ] "Tipe" [] ]
                                                , output = [ AST.InternalRef [ "internal" ] "Tope" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.PackageWord emptyRange [ "internal" ] "value"
                                                , AST.PackageWord emptyRange [ "ext" ] "add"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.isExposed False
                                                |> Metadata.withType
                                                    [ Type.Custom "/external/package/mod/Tipe"
                                                    ]
                                                    [ Type.Custom "internal/mod/Tope" ]
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Word emptyRange "internal/mod/value"
                                                , Word emptyRange "/external/package/mod/add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe"
                                , dummyType "internal/mod/Tope"
                                ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words =
                                Dict.fromList
                                    [ dummyWord "/external/package/mod/add"
                                    , dummyWord "internal/mod/value"
                                    ]
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Module and function aliases" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases =
                                        Dict.fromList
                                            [ ( "ext", "/mod" ) ]
                                    , imports = Dict.empty
                                    , exposes = Set.empty
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.InternalRef [ "ext" ] "Tipe" [] ]
                                                , output = [ AST.InternalRef [ "internal" ] "Tope" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.fromList [ ( "internal", "internal/mod" ) ]
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.PackageWord emptyRange [ "internal" ] "value"
                                                , AST.PackageWord emptyRange [ "ext" ] "add"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.isExposed False
                                                |> Metadata.withType
                                                    [ Type.Custom "/external/package/mod/Tipe"
                                                    ]
                                                    [ Type.Custom "internal/mod/Tope" ]
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Word emptyRange "internal/mod/value"
                                                , Word emptyRange "/external/package/mod/add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe"
                                , dummyType "internal/mod/Tope"
                                ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words =
                                Dict.fromList
                                    [ dummyWord "/external/package/mod/add"
                                    , dummyWord "internal/mod/value"
                                    ]
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Module and function aliases in type match" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases =
                                        Dict.fromList
                                            [ ( "ext", "/mod" ) ]
                                    , imports = Dict.empty
                                    , exposes = Set.empty
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.fromList [ ( "internal", "internal/mod" ) ]
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.InternalRef [ "ext" ] "Tipe" []) []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                , ( AST.TypeMatch emptyRange (AST.InternalRef [ "internal" ] "Tope" []) []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "drop" ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.isExposed False
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Type.Custom "/external/package/mod/Tipe") []
                                                  , [ Builtin emptyRange Builtin.StackDrop ]
                                                  )
                                                , ( TypeMatch emptyRange (Type.Custom "internal/mod/Tope") []
                                                  , [ Builtin emptyRange Builtin.StackDrop ]
                                                  )
                                                ]
                                                [ Builtin emptyRange Builtin.StackDrop ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe"
                                , dummyType "internal/mod/Tope"
                                ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Type definition aliases" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases =
                                        Dict.fromList
                                            [ ( "ext", "/mod" )
                                            , ( "mod", "internal/mod" )
                                            ]
                                    , imports = Dict.empty
                                    , exposes = Set.empty
                                    }
                            , types =
                                Dict.fromList
                                    [ ( "Tepip"
                                      , AST.CustomTypeDef
                                            emptyRange
                                            "Tepip"
                                            []
                                            [ ( "first", AST.InternalRef [ "ext" ] "Tipe" [] )
                                            , ( "second", AST.InternalRef [ "mod" ] "Tope" [] )
                                            ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        expectedAst =
                            { types =
                                Dict.fromList
                                    [ ( "Tepip"
                                      , CustomTypeDef
                                            "Tepip"
                                            True
                                            emptyRange
                                            []
                                            [ ( "first", Type.Custom "/external/package/mod/Tipe" )
                                            , ( "second", Type.Custom "internal/mod/Tope" )
                                            ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe"
                                , dummyType "internal/mod/Tope"
                                ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Module imports" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases = Dict.empty
                                    , imports =
                                        Dict.fromList
                                            [ ( "/mod", [ "add", "Tipe" ] )
                                            , ( "internal/mod", [] )
                                            ]
                                    , exposes = Set.empty
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.LocalRef "Tipe" [] ]
                                                , output = [ AST.LocalRef "Tope" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "value"
                                                , AST.Word emptyRange "add"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.isExposed False
                                                |> Metadata.withType
                                                    [ Type.Custom "/external/package/mod/Tipe" ]
                                                    [ Type.Custom "internal/mod/Tope" ]
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Word emptyRange "internal/mod/value"
                                                , Word emptyRange "/external/package/mod/add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe"
                                , dummyType "internal/mod/Tope"
                                ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words =
                                Dict.fromList
                                    [ dummyWord "/external/package/mod/add"
                                    , dummyWord "internal/mod/value"
                                    ]
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Module and function imports" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases = Dict.empty
                                    , imports =
                                        Dict.fromList
                                            [ ( "internal/mod", [] )
                                            ]
                                    , exposes = Set.empty
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.LocalRef "Tipe" [] ]
                                                , output = [ AST.LocalRef "Tope" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.fromList [ ( "/mod", [ "add", "Tipe" ] ) ]
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "value"
                                                , AST.Word emptyRange "add"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.isExposed False
                                                |> Metadata.withType
                                                    [ Type.Custom "/external/package/mod/Tipe" ]
                                                    [ Type.Custom "internal/mod/Tope" ]
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Word emptyRange "internal/mod/value"
                                                , Word emptyRange "/external/package/mod/add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe"
                                , dummyType "internal/mod/Tope"
                                ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words =
                                Dict.fromList
                                    [ dummyWord "/external/package/mod/add"
                                    , dummyWord "internal/mod/value"
                                    ]
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Type definition imports" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases = Dict.empty
                                    , imports =
                                        Dict.fromList
                                            [ ( "/mod", [] )
                                            , ( "internal/mod", [ "Tope" ] )
                                            ]
                                    , exposes = Set.empty
                                    }
                            , types =
                                Dict.fromList
                                    [ ( "Tepip"
                                      , AST.CustomTypeDef
                                            emptyRange
                                            "Tepip"
                                            []
                                            [ ( "first", AST.LocalRef "Tipe" [] )
                                            , ( "second", AST.LocalRef "Tope" [] )
                                            ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        expectedAst =
                            { types =
                                Dict.fromList
                                    [ ( "Tepip"
                                      , CustomTypeDef
                                            "Tepip"
                                            True
                                            emptyRange
                                            []
                                            [ ( "first", Type.Custom "/external/package/mod/Tipe" )
                                            , ( "second", Type.Custom "internal/mod/Tope" )
                                            ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe"
                                , dummyType "internal/mod/Tope"
                                ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "Module and function imports in type match" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases = Dict.empty
                                    , imports =
                                        Dict.fromList
                                            [ ( "/mod", [ "Tipe" ] ) ]
                                    , exposes = Set.empty
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports =
                                            Dict.fromList
                                                [ ( "internal/mod", [] ) ]
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.LocalRef "Tipe" []) []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                , ( AST.TypeMatch emptyRange (AST.LocalRef "Tope" []) []
                                                  , [ AST.Word emptyRange "drop" ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "drop" ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.isExposed False
                                      , implementation =
                                            MultiImpl
                                                [ ( TypeMatch emptyRange (Type.Custom "/external/package/mod/Tipe") []
                                                  , [ Builtin emptyRange Builtin.StackDrop ]
                                                  )
                                                , ( TypeMatch emptyRange (Type.Custom "internal/mod/Tope") []
                                                  , [ Builtin emptyRange Builtin.StackDrop ]
                                                  )
                                                ]
                                                [ Builtin emptyRange Builtin.StackDrop ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                [ dummyType "/external/package/mod/Tipe"
                                , dummyType "internal/mod/Tope"
                                ]
                                    |> List.concat
                                    |> Dict.fromList
                            , words = Dict.empty
                            }
                    in
                    QualifierUtil.expectExternalOutput
                        inProgressAst
                        unqualifiedAst
                        expectedAst
            , test "When module doesn't have a definition, all functions are exposed" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.Undefined
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "fn1"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Integer emptyRange 2
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    , { name = "fn2"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 2
                                                , AST.Integer emptyRange 3
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "fn1"
                                      , metadata = Metadata.default
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Integer emptyRange 2
                                                , Builtin emptyRange Builtin.Plus
                                                ]
                                      }
                                    , { name = "fn2"
                                      , metadata = Metadata.default
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 2
                                                , Integer emptyRange 3
                                                , Builtin emptyRange Builtin.Plus
                                                ]
                                      }
                                    ]
                            }
                    in
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            , test "When module does have a definition, only functions defined to be exposed are" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases = Dict.empty
                                    , imports = Dict.empty
                                    , exposes = Set.fromList [ "fn2" ]
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "fn1"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Integer emptyRange 2
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    , { name = "fn2"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 2
                                                , AST.Integer emptyRange 3
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    ]
                            }

                        expectedAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "fn1"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.isExposed False
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 1
                                                , Integer emptyRange 2
                                                , Builtin emptyRange Builtin.Plus
                                                ]
                                      }
                                    , { name = "fn2"
                                      , metadata = Metadata.default
                                      , implementation =
                                            SoloImpl
                                                [ Integer emptyRange 2
                                                , Integer emptyRange 3
                                                , Builtin emptyRange Builtin.Plus
                                                ]
                                      }
                                    ]
                            }
                    in
                    QualifierUtil.expectOutput unqualifiedAst expectedAst
            , test "Referencing a function from an internal module which isn't exposed ends in a error" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases = Dict.empty
                                    , imports =
                                        Dict.fromList

                                            [ ( "internal/mod", [] )
                                            ]
                                    , exposes = Set.empty

                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "value"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromList

                                    [ dummyWordUnexposed "internal/mod/value"
                                    ]
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList
                                        [ ( "/mod", "external/package" ) ]
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->
                            Expect.fail "Expected qualification to fail because an unexposed function is called"

                        Err [ Problem.WordNotExposed _ "internal/mod/value" ] ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "Referencing a function from an external module which isn't exposed ends in a error" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { aliases = Dict.empty
                                    , imports =
                                        Dict.fromList
                                            [ ( "/mod", [ "add" ] )
                                            ]
                                    , exposes = Set.empty
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name


                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "add"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromList
                                    [ dummyWordUnexposed "/external/package/mod/add"
                                    ]
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList
                                        [ ( "/mod", "external/package" ) ]
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->

                            Expect.fail "Expected qualification to fail because an unexposed function is called"




                        Err [ Problem.WordNotExposed _ "/external/package/mod/add" ] ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "Referencing a type in a type signature from an external module which isn't exposed ends in a error" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.Undefined
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"

                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.ExternalRef [ "mod" ] "Tipe" [] ]
                                                , output = []
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl

                                                [ AST.Word emptyRange "drop"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                Dict.fromList <|
                                    dummyTypeUnexposed "/external/package/mod/Tipe"
                            , words = Dict.empty
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList
                                        [ ( "/mod", "external/package" ) ]
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->
                            Expect.fail "Expected qualification to fail because an unexposed type is referenced"

                        Err [ Problem.TypeNotExposed _ "/external/package/mod/Tipe" ] ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "Referencing a type in a type definition from an external module which isn't exposed ends in a error" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.Undefined
                            , types =
                                Dict.fromList
                                    [ ( "BoxedTipe"
                                      , AST.CustomTypeDef
                                            emptyRange
                                            "BoxedTipe"
                                            []
                                            [ ( "value", AST.ExternalRef [ "mod" ] "TipeUnion" [] ) ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        inProgressAst =
                            { types =
                                Dict.fromList <|
                                    dummyTypeUnexposed "/external/package/mod/Tipe"
                            , words = Dict.empty
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList



                                        [ ( "/mod", "external/package" ) ]
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->
                            Expect.fail "Expected qualification to fail because an unexposed type is referenced"

                        Err [ Problem.TypeNotExposed _ "/external/package/mod/TipeUnion" ] ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "Referencing a type in a type match from an external module which isn't exposed ends in a error" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.Undefined
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.ExternalRef [ "mod" ] "Tipe" []) []
                                                  , [ AST.Word emptyRange "drop"
                                                    ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "drop"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                Dict.fromList <|
                                    dummyTypeUnexposed "/external/package/mod/Tipe"
                            , words = Dict.empty
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList

                                        [ ( "/mod", "external/package" ) ]
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->
                            Expect.fail "Expected qualification to fail because an unexposed type is referenced"

                        Err [ Problem.TypeNotExposed _ "/external/package/mod/Tipe" ] ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "Referencing a type in a type signature from an internal module which isn't exposed ends in a error" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.Undefined
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name


                                    [ { name = "external-call"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.InternalRef [ "mod" ] "Tipe" [] ]
                                                , output = []
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Word emptyRange "drop"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                Dict.fromList <|
                                    dummyTypeUnexposed "mod/Tipe"
                            , words = Dict.empty
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules = Dict.empty
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->
                            Expect.fail "Expected qualification to fail because an unexposed type is referenced"

                        Err [ Problem.TypeNotExposed _ "mod/Tipe" ] ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "Referencing a type in a type definition from an internal module which isn't exposed ends in a error" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.Undefined
                            , types =
                                Dict.fromList
                                    [ ( "BoxedTipe"
                                      , AST.CustomTypeDef
                                            emptyRange
                                            "BoxedTipe"
                                            []
                                            [ ( "value", AST.InternalRef [ "mod" ] "TipeUnion" [] ) ]
                                      )
                                    ]
                            , words = Dict.empty
                            }

                        inProgressAst =
                            { types =
                                Dict.fromList <|
                                    dummyTypeUnexposed "mod/Tipe"
                            , words = Dict.empty
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules = Dict.empty
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->
                            Expect.fail "Expected qualification to fail because an unexposed type is referenced"

                        Err [ Problem.TypeNotExposed _ "mod/TipeUnion" ] ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "Referencing a type in a type match from an internal module which isn't exposed ends in a error" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.Undefined
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.MultiImpl
                                                [ ( AST.TypeMatch emptyRange (AST.InternalRef [ "mod" ] "Tipe" []) []
                                                  , [ AST.Word emptyRange "drop"
                                                    ]
                                                  )
                                                ]
                                                [ AST.Word emptyRange "drop"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types =
                                Dict.fromList <|
                                    dummyTypeUnexposed "mod/Tipe"
                            , words = Dict.empty
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules = Dict.empty
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->
                            Expect.fail "Expected qualification to fail because an unexposed type is referenced"

                        Err [ Problem.TypeNotExposed _ "mod/Tipe" ] ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "There's an implicit import on standard_library/core in anonymous modules" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition = AST.Undefined
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Word emptyRange "over"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromList
                                    [ dummyWord "/play/standard_library/core/over" ]
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList
                                        [ ( "/core", "play/standard_library" ) ]
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of
                        Ok _ ->
                            Expect.pass

                        Err errs ->
                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            , test "There's an implicit import on standard_library/core in named modules" <|
                \_ ->
                    let
                        unqualifiedAst =
                            { moduleDefinition =
                                AST.Defined
                                    { imports = Dict.empty
                                    , aliases = Dict.empty
                                    , exposes = Set.empty
                                    }
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "external-call"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Word emptyRange "over"
                                                ]
                                      }
                                    ]
                            }

                        inProgressAst =
                            { types = Dict.empty
                            , words =
                                Dict.fromList
                                    [ dummyWord "/play/standard_library/core/over" ]
                            }

                        result =
                            run
                                { packageName = ""
                                , modulePath = ""
                                , ast = unqualifiedAst
                                , externalModules =
                                    Dict.fromList
                                        [ ( "/core", "play/standard_library" ) ]
                                , inProgressAST = inProgressAst
                                }
                    in
                    case result of






                        Ok _ ->



















                            Expect.pass



































                        Err errs ->

                            Expect.fail <| "Qualification failed with unexpected error: " ++ Debug.toString errs
            ]















        ]





















































Modified tests/Test/Qualifier/Error.elm from [42c36a26bb] to [0f9091b125].

16
17
18
19
20
21
22

23
24
25
26
27



28
29
30
31
32
33
34
35
36
37

38
39
40
41
42
43
44
..
49
50
51
52
53
54
55

56
57
58
59
60
61
62

63
64
65
66
67
68
69
..
70
71
72
73
74
75
76

77
78
79
80
81
82
83





84
85
86
87
88
89
90
91
92
93

94
95
96
97
98
99
100
...
103
104
105
106
107
108
109

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

133
134
135
136
137
138
139
140
141
142
143
144
145
146
...
171
172
173
174
175
176
177




178
179
180
181
182
183
184
185
186
187
188
189
suite =
    describe "Qualifier errors"
        [ describe "No such reference" <|
            [ test "Word" <|
                \_ ->
                    let
                        ast =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "inc"
                                      , metadata = Metadata.default



                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    , { name = "main"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint

                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "inc"
                                                , AST.Word emptyRange "inc"
                                                , AST.Word emptyRange "dec"
                                                , AST.Integer emptyRange 2
................................................................................
                            }
                    in
                    checkForError (noSuchWordReferenceError "dec") ast
            , test "External" <|
                \_ ->
                    let
                        ast =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "main"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint

                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "/external/module/inc"
                                                ]
                                      }
                                    ]
................................................................................
                            }
                    in
                    checkForError (noSuchWordReferenceError "/external/module/inc") ast
            , test "Type" <|
                \_ ->
                    let
                        ast =

                            { types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "inc"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType [ Type.Custom "Ints" ] [ Type.Int ]





                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    , { name = "main"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint

                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "inc"
                                                , AST.Integer emptyRange 2
                                                , AST.Word emptyRange "="
                                                ]
................................................................................
                            }
                    in
                    checkForError (noSuchTypeReferenceError "Ints") ast
            , test "Wrong reference within union definition" <|
                \_ ->
                    let
                        ast =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ AST.UnionTypeDef
                                        emptyRange
                                        "USMoney"
                                        []
                                        [ Type.Custom "Dollar"
                                        , Type.Custom "Cent"
                                        ]
                                    , AST.CustomTypeDef
                                        emptyRange
                                        "Dollar"
                                        []
                                        [ ( "dollar-value", Type.Int ) ]
                                    ]
                            , words = Dict.empty
                            }
                    in
                    checkForError (noSuchTypeReferenceError "Cent") ast
            , test "Wrong reference within custom type definition" <|
                \_ ->
                    let
                        ast =

                            { types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ AST.CustomTypeDef
                                        emptyRange
                                        "BoxWrapper"
                                        []
                                        [ ( "box", Type.Custom "Box" ) ]
                                    ]
                            , words = Dict.empty
                            }
                    in
                    checkForError (noSuchTypeReferenceError "Box") ast
            ]
        ]
................................................................................
    let
        result =
            run
                { packageName = ""
                , modulePath = ""
                , ast = source
                , externalModules = Dict.empty




                }
    in
    case result of
        Err errors ->
            if List.any fn errors then
                Expect.pass

            else
                Expect.fail <| "Failed for unexpected reason: " ++ Debug.toString errors

        Ok _ ->
            Expect.fail "Did not expect parsing to succeed"







>
|



|
>
>
>







|
|
|
>







 







>
|



|
|
|
>







 







>
|



|
|
|
>
>
>
>
>







|
|
|
>







 







>
|





|
|





|









>
|





|







 







>
>
>
>












16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
..
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
..
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
...
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
suite =
    describe "Qualifier errors"
        [ describe "No such reference" <|
            [ test "Word" <|
                \_ ->
                    let
                        ast =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "inc"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    , { name = "main"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "inc"
                                                , AST.Word emptyRange "inc"
                                                , AST.Word emptyRange "dec"
                                                , AST.Integer emptyRange 2
................................................................................
                            }
                    in
                    checkForError (noSuchWordReferenceError "dec") ast
            , test "External" <|
                \_ ->
                    let
                        ast =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "main"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "/external/module/inc"
                                                ]
                                      }
                                    ]
................................................................................
                            }
                    in
                    checkForError (noSuchWordReferenceError "/external/module/inc") ast
            , test "Type" <|
                \_ ->
                    let
                        ast =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types = Dict.empty
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "inc"
                                      , typeSignature =
                                            AST.UserProvided
                                                { input = [ AST.LocalRef "Ints" [] ]
                                                , output = [ AST.LocalRef "Int" [] ]
                                                }
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "+"
                                                ]
                                      }
                                    , { name = "main"
                                      , typeSignature = AST.NotProvided
                                      , sourceLocationRange = Nothing
                                      , aliases = Dict.empty
                                      , imports = Dict.empty
                                      , implementation =
                                            AST.SoloImpl
                                                [ AST.Integer emptyRange 1
                                                , AST.Word emptyRange "inc"
                                                , AST.Integer emptyRange 2
                                                , AST.Word emptyRange "="
                                                ]
................................................................................
                            }
                    in
                    checkForError (noSuchTypeReferenceError "Ints") ast
            , test "Wrong reference within union definition" <|
                \_ ->
                    let
                        ast =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ AST.UnionTypeDef
                                        emptyRange
                                        "USMoney"
                                        []
                                        [ AST.LocalRef "Dollar" []
                                        , AST.LocalRef "Cent" []
                                        ]
                                    , AST.CustomTypeDef
                                        emptyRange
                                        "Dollar"
                                        []
                                        [ ( "dollar-value", AST.LocalRef "Int" [] ) ]
                                    ]
                            , words = Dict.empty
                            }
                    in
                    checkForError (noSuchTypeReferenceError "Cent") ast
            , test "Wrong reference within custom type definition" <|
                \_ ->
                    let
                        ast =
                            { moduleDefinition = AST.emptyModuleDefinition
                            , types =
                                Dict.fromListBy AST.typeDefinitionName
                                    [ AST.CustomTypeDef
                                        emptyRange
                                        "BoxWrapper"
                                        []
                                        [ ( "box", AST.LocalRef "Box" [] ) ]
                                    ]
                            , words = Dict.empty
                            }
                    in
                    checkForError (noSuchTypeReferenceError "Box") ast
            ]
        ]
................................................................................
    let
        result =
            run
                { packageName = ""
                , modulePath = ""
                , ast = source
                , externalModules = Dict.empty
                , inProgressAST =
                    { types = Dict.empty
                    , words = Dict.empty
                    }
                }
    in
    case result of
        Err errors ->
            if List.any fn errors then
                Expect.pass

            else
                Expect.fail <| "Failed for unexpected reason: " ++ Debug.toString errors

        Ok _ ->
            Expect.fail "Did not expect parsing to succeed"

Modified tests/Test/Qualifier/Util.elm from [f85a91ec9e] to [d1d2da2384].

1
2

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39
40
41
























42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63



64



65
66





67
68
69
70

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
...
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
module Test.Qualifier.Util exposing
    ( addFunctionsForStructs

    , expectModuleOutput
    , expectOutput
    , stripLocations
    )

import Dict exposing (Dict)
import Dict.Extra as Dict
import Expect exposing (Expectation)
import Play.Data.Metadata as Metadata
import Play.Data.SourceLocation exposing (emptyRange)
import Play.Data.Type as Type exposing (Type)
import Play.Parser as Parser
import Play.Qualifier as AST
    exposing
        ( ExposedAST
        , Node(..)
        , TypeDefinition
        , TypeMatch(..)
        , TypeMatchValue(..)
        , WordDefinition
        , WordImplementation(..)
        )


type alias FullyLoadedAST =
    { types : Dict String TypeDefinition
    , words : Dict String WordDefinition

    }


expectOutput : Parser.AST -> FullyLoadedAST -> Expectation
expectOutput parserAst expectedAst =
    let
        result =
            AST.run
                { packageName = ""
                , modulePath = ""
                , ast = parserAst
                , externalModules = Dict.empty
























                }
    in
    case result of
        Err errors ->
            Expect.fail <| "Did not expect qualification to fail. Errors: " ++ Debug.toString errors

        Ok actualAst ->
            Expect.equal expectedAst
                { types = actualAst.types
                , words = actualAst.words
                }


expectModuleOutput : Parser.AST -> FullyLoadedAST -> Expectation
expectModuleOutput parserAst expectedAst =
    let
        result =
            AST.run
                { packageName = "play/test"
                , modulePath = "some/module"
                , ast = parserAst
                , externalModules = Dict.empty



                }



    in
    case result of





        Err errors ->
            Expect.fail <| "Did not expect qualification to fail. Errors: " ++ Debug.toString errors

        Ok actualAst ->

            Expect.equal expectedAst
                { types = actualAst.types
                , words = actualAst.words
                }


addFunctionsForStructs : FullyLoadedAST -> FullyLoadedAST
addFunctionsForStructs ast =
    let
        helper _ t wipAst =
            case t of
                AST.CustomTypeDef name _ generics members ->
                    addFunctionsForStructsHelper name generics members wipAst

                _ ->
                    wipAst
    in
    Dict.foldl helper ast ast.types


addFunctionsForStructsHelper : String -> List String -> List ( String, Type ) -> FullyLoadedAST -> FullyLoadedAST
addFunctionsForStructsHelper name generics members ast =
    let
        selfType =
            if List.isEmpty generics then
                Type.Custom name

            else
................................................................................
            (ctor :: setters)
                ++ getters
                |> Dict.fromListBy .name
    in
    { ast | words = Dict.union ast.words allFuncs }


stripLocations : ExposedAST -> ExposedAST
stripLocations ast =
    { types = Dict.map (\_ t -> stripTypeLocation t) ast.types
    , words = Dict.map (\_ d -> stripWordLocation d) ast.words
    }


stripTypeLocation : TypeDefinition -> TypeDefinition
stripTypeLocation typeDef =
    case typeDef of
        AST.CustomTypeDef name _ generics members ->
            AST.CustomTypeDef name emptyRange generics members

        AST.UnionTypeDef name _ generics members ->
            AST.UnionTypeDef name emptyRange generics members


stripWordLocation : WordDefinition -> WordDefinition
stripWordLocation word =
    { word
        | implementation = stripImplementationLocation word.implementation
        , metadata = Metadata.clearSourceLocationRange word.metadata


>





|








|









|
|
|
>



|








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













|
|

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


>
>
>
>
>
|
|

<
>
|
<
<
|

<
|




|








|







 







|









|
|

|
|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

106
107


108
109

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
...
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
module Test.Qualifier.Util exposing
    ( addFunctionsForStructs
    , expectExternalOutput
    , expectModuleOutput
    , expectOutput
    , stripLocations
    )

import Dict
import Dict.Extra as Dict
import Expect exposing (Expectation)
import Play.Data.Metadata as Metadata
import Play.Data.SourceLocation exposing (emptyRange)
import Play.Data.Type as Type exposing (Type)
import Play.Parser as Parser
import Play.Qualifier as AST
    exposing
        ( AST
        , Node(..)
        , TypeDefinition
        , TypeMatch(..)
        , TypeMatchValue(..)
        , WordDefinition
        , WordImplementation(..)
        )


emptyAst : AST
emptyAst =
    { types = Dict.empty
    , words = Dict.empty
    }


expectOutput : Parser.AST -> AST -> Expectation
expectOutput parserAst expectedAst =
    let
        result =
            AST.run
                { packageName = ""
                , modulePath = ""
                , ast = parserAst
                , externalModules = Dict.empty
                , inProgressAST = emptyAst
                }
    in
    case result of
        Err errors ->
            Expect.fail <| "Did not expect qualification to fail. Errors: " ++ Debug.toString errors

        Ok actualAst ->
            Expect.equal expectedAst
                { types = actualAst.types
                , words = actualAst.words
                }


expectModuleOutput : Parser.AST -> AST -> Expectation
expectModuleOutput parserAst expectedAst =
    let
        result =
            AST.run
                { packageName = "play/test"
                , modulePath = "some/module"
                , ast = parserAst
                , externalModules = Dict.empty
                , inProgressAST = emptyAst
                }
    in
    case result of
        Err errors ->
            Expect.fail <| "Did not expect qualification to fail. Errors: " ++ Debug.toString errors

        Ok actualAst ->
            Expect.equal expectedAst
                { types = actualAst.types
                , words = actualAst.words
                }


expectExternalOutput : AST -> Parser.AST -> AST -> Expectation
expectExternalOutput inProgressAst parserAst expectedAst =
    let
        config =

            { packageName = ""
            , modulePath = ""
            , ast = parserAst
            , externalModules =
                Dict.fromList
                    [ ( "/mod", "external/package" ) ]
            , inProgressAST = emptyAst
            }

        result =
            AST.run config
    in
    case result of
        Ok _ ->
            Expect.fail "Expected qualification to fail when inProgressAST is missing"

        Err _ ->
            case AST.run { config | inProgressAST = inProgressAst } of
                Err errors ->
                    Expect.fail <| "Did not expect qualification to fail: " ++ Debug.toString errors


                Ok ast ->
                    Expect.equal expectedAst ast





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

                _ ->
                    wipAst
    in
    Dict.foldl helper ast ast.types


addFunctionsForStructsHelper : String -> List String -> List ( String, Type ) -> AST -> AST
addFunctionsForStructsHelper name generics members ast =
    let
        selfType =
            if List.isEmpty generics then
                Type.Custom name

            else
................................................................................
            (ctor :: setters)
                ++ getters
                |> Dict.fromListBy .name
    in
    { ast | words = Dict.union ast.words allFuncs }


stripLocations : AST -> AST
stripLocations ast =
    { types = Dict.map (\_ t -> stripTypeLocation t) ast.types
    , words = Dict.map (\_ d -> stripWordLocation d) ast.words
    }


stripTypeLocation : TypeDefinition -> TypeDefinition
stripTypeLocation typeDef =
    case typeDef of
        AST.CustomTypeDef exposed name _ generics members ->
            AST.CustomTypeDef exposed name emptyRange generics members

        AST.UnionTypeDef exposed name _ generics members ->
            AST.UnionTypeDef exposed name emptyRange generics members


stripWordLocation : WordDefinition -> WordDefinition
stripWordLocation word =
    { word
        | implementation = stripImplementationLocation word.implementation
        , metadata = Metadata.clearSourceLocationRange word.metadata

Modified tests/Test/TypeChecker.elm from [51729be1c5] to [5cf7f1ff07].

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
...
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
...
299
300
301
302
303
304
305

306
307
308
309
310
311
312
...
337
338
339
340
341
342
343

344
345
346
347
348
349
350
...
411
412
413
414
415
416
417

418
419
420
421
422
423

424
425
426
427

428
429
430
431
432
433
434
435
436
437
438
439
440
...
601
602
603
604
605
606
607




608
609
610
611
612
613
614
615
...
620
621
622
623
624
625
626




627
628
629
630
631
632
633
634
...
645
646
647
648
649
650
651

652
653
654
655
656
657
658
659
660
661
662
663
664
665
...
794
795
796
797
798
799
800

801
802
803
804
805
806

807
808
809
810

811
812
813
814
815
816
817
...
878
879
880
881
882
883
884

885
886
887
888
889
890
891
892
893
894
895
896
897
898
...
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
....
1023
1024
1025
1026
1027
1028
1029

1030
1031
1032
1033
1034
1035




1036
1037
1038
1039
1040
1041
1042
....
1150
1151
1152
1153
1154
1155
1156

1157
1158
1159
1160
1161
1162




1163
1164
1165
1166
1167
1168
1169
....
1410
1411
1412
1413
1414
1415
1416

1417
1418
1419
1420
1421
1422




1423
1424
1425
1426
1427
1428
1429
....
1489
1490
1491
1492
1493
1494
1495

1496
1497
1498
1499
1500
1501

1502
1503
1504
1505
1506
1507




1508
1509
1510
1511
1512
1513
1514
                        Expect.fail "Did not expect type check to succeed."
        , test "Custom data structure without fields" <|
            \_ ->
                let
                    source =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "True" emptyRange [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "as-int"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [] [ Type.Int ]
................................................................................
                        Expect.pass
        , test "Custom data structure with fields" <|
            \_ ->
                let
                    source =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Person" emptyRange [] [ ( "age", Type.Int ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "inc-age"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [ Type.Custom "Person" ] [ Type.Custom "Person" ]
................................................................................
        , test "Generic custom type" <|
            \_ ->
                let
                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Box"

                                    emptyRange
                                    [ "a" ]
                                    [ ( "element", Type.Generic "a" ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
................................................................................
        , test "Generic types with rotations and quotations" <|
            \_ ->
                let
                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Coordinate"

                                    emptyRange
                                    []
                                    [ ( "x", Type.Int )
                                    , ( "y", Type.Int )
                                    ]
                                ]
                        , words =
................................................................................
                        , Type.CustomGeneric "NonEmpty" [ Type.Generic "a" ]
                        ]

                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Pair"

                                    emptyRange
                                    [ "a", "b" ]
                                    [ ( "first", Type.Generic "a" )
                                    , ( "second", Type.Generic "b" )
                                    ]
                                , QAST.UnionTypeDef "List"

                                    emptyRange
                                    [ "a" ]
                                    listUnion
                                , QAST.CustomTypeDef "NonEmpty"

                                    emptyRange
                                    [ "a" ]
                                    [ ( "head", Type.Generic "a" )
                                    , ( "rest", Type.Union listUnion )
                                    ]
                                , QAST.CustomTypeDef "Empty" emptyRange [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [] [ Type.Int ]
................................................................................
                        Expect.pass
        , test "Generic custom type fails if not generic is listed" <|
            \_ ->
                let
                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName




                                [ QAST.CustomTypeDef "Box" emptyRange [] [ ( "element", Type.Generic "a" ) ]
                                ]
                        , words =
                            Dict.empty
                        }
                            |> QualifierUtil.addFunctionsForStructs
                in
                case run input of
................................................................................
                        Expect.pass
        , test "Generic custom type fails if wrong generic is listed" <|
            \_ ->
                let
                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName




                                [ QAST.CustomTypeDef "Box" emptyRange [ "a" ] [ ( "element", Type.Generic "b" ) ]
                                ]
                        , words =
                            Dict.empty
                        }
                            |> QualifierUtil.addFunctionsForStructs
                in
                case run input of
................................................................................
                        , Type.Custom "False"
                        ]

                template multiFn =
                    { types =
                        Dict.fromListBy QAST.typeDefinitionName
                            [ QAST.UnionTypeDef "Bool"

                                emptyRange
                                []
                                [ Type.Custom "True"
                                , Type.Custom "False"
                                ]
                            , QAST.CustomTypeDef "True" emptyRange [] []
                            , QAST.CustomTypeDef "False" emptyRange [] []
                            ]
                    , words =
                        Dict.fromListBy .name
                            [ multiFn
                            , { name = "main"
                              , metadata =
                                    Metadata.default
................................................................................
            , test "When returning union" <|
                \_ ->
                    let
                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Beings"

                                        emptyRange
                                        []
                                        [ Type.Custom "Person"
                                        , Type.Custom "Dog"
                                        ]
                                    , QAST.CustomTypeDef "Person"

                                        emptyRange
                                        []
                                        [ ( "age", Type.Int ) ]
                                    , QAST.CustomTypeDef "Dog"

                                        emptyRange
                                        []
                                        [ ( "man-years", Type.Int ) ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "add-to-age"
................................................................................
            , test "Function requiring a concrete type should not accept an union with that type" <|
                \_ ->
                    let
                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Bool"

                                        emptyRange
                                        []
                                        [ Type.Custom "True"
                                        , Type.Custom "False"
                                        ]
                                    , QAST.CustomTypeDef "True" emptyRange [] []
                                    , QAST.CustomTypeDef "False" emptyRange [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "not"
                                      , metadata = Metadata.default
                                      , implementation =
                                            QAST.MultiImpl
................................................................................
                                , Type.Custom "EmptyList"
                                ]

                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "List"

                                        emptyRange
                                        [ "a" ]
                                        [ Type.CustomGeneric "NonEmptyList" [ Type.Generic "a" ]
                                        , Type.Custom "EmptyList"
                                        ]
                                    , QAST.CustomTypeDef "NonEmptyList"

                                        emptyRange
                                        [ "a" ]
                                        [ ( "first", Type.Generic "a" )
                                        , ( "rest", listUnion )
                                        ]
                                    , QAST.CustomTypeDef "EmptyList" emptyRange [] []




                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "first-or-default"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
................................................................................
                                , Type.Custom "Nil"
                                ]

                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Maybe"

                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nil"
                                        ]
                                    , QAST.CustomTypeDef "Nil" emptyRange [] []




                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "with-default"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
................................................................................
            , test "Generic union fails if not generic is listed" <|
                \_ ->
                    let
                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Maybe"

                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "b"
                                        , Type.Custom "Nothing"
                                        ]
                                    , QAST.CustomTypeDef "Nothing" emptyRange [] []




                                    ]
                            , words =
                                Dict.empty
                            }
                                |> QualifierUtil.addFunctionsForStructs
                    in
                    case run input of
................................................................................
                                , Type.Custom "Nil"
                                ]

                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Maybe"

                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nil"
                                        ]
                                    , QAST.CustomTypeDef "Nil" emptyRange [] []




                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "map"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
................................................................................
                                , Type.Custom "EmptyList"
                                ]

                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "List"

                                        emptyRange
                                        [ "a" ]
                                        [ Type.CustomGeneric "NonEmptyList" [ Type.Generic "a" ]
                                        , Type.Custom "EmptyList"
                                        ]
                                    , QAST.CustomTypeDef "NonEmptyList"

                                        emptyRange
                                        [ "a" ]
                                        [ ( "first", Type.Generic "a" )
                                        , ( "rest", listUnion )
                                        ]
                                    , QAST.CustomTypeDef "EmptyList" emptyRange [] []




                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "sum"
                                      , metadata = Metadata.default
                                      , implementation =
                                            QAST.SoloImpl







|







 







|







 







>







 







>







 







>






>




>





|







 







>
>
>
>
|







 







>
>
>
>
|







 







>





|
|







 







>






>




>







 







>





|
|







 







>






>





|
>
>
>
>







 







>





|
>
>
>
>







 







>





|
>
>
>
>







 







>





|
>
>
>
>







 







>






>





|
>
>
>
>







132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
...
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
...
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
...
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
...
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
...
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
...
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
...
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
...
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
...
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
....
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
....
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
....
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
....
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
                        Expect.fail "Did not expect type check to succeed."
        , test "Custom data structure without fields" <|
            \_ ->
                let
                    source =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "True" True emptyRange [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "as-int"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [] [ Type.Int ]
................................................................................
                        Expect.pass
        , test "Custom data structure with fields" <|
            \_ ->
                let
                    source =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Person" True emptyRange [] [ ( "age", Type.Int ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "inc-age"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [ Type.Custom "Person" ] [ Type.Custom "Person" ]
................................................................................
        , test "Generic custom type" <|
            \_ ->
                let
                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Box"
                                    True
                                    emptyRange
                                    [ "a" ]
                                    [ ( "element", Type.Generic "a" ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
................................................................................
        , test "Generic types with rotations and quotations" <|
            \_ ->
                let
                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Coordinate"
                                    True
                                    emptyRange
                                    []
                                    [ ( "x", Type.Int )
                                    , ( "y", Type.Int )
                                    ]
                                ]
                        , words =
................................................................................
                        , Type.CustomGeneric "NonEmpty" [ Type.Generic "a" ]
                        ]

                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Pair"
                                    True
                                    emptyRange
                                    [ "a", "b" ]
                                    [ ( "first", Type.Generic "a" )
                                    , ( "second", Type.Generic "b" )
                                    ]
                                , QAST.UnionTypeDef "List"
                                    True
                                    emptyRange
                                    [ "a" ]
                                    listUnion
                                , QAST.CustomTypeDef "NonEmpty"
                                    True
                                    emptyRange
                                    [ "a" ]
                                    [ ( "head", Type.Generic "a" )
                                    , ( "rest", Type.Union listUnion )
                                    ]
                                , QAST.CustomTypeDef "Empty" True emptyRange [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [] [ Type.Int ]
................................................................................
                        Expect.pass
        , test "Generic custom type fails if not generic is listed" <|
            \_ ->
                let
                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Box"
                                    True
                                    emptyRange
                                    []
                                    [ ( "element", Type.Generic "a" ) ]
                                ]
                        , words =
                            Dict.empty
                        }
                            |> QualifierUtil.addFunctionsForStructs
                in
                case run input of
................................................................................
                        Expect.pass
        , test "Generic custom type fails if wrong generic is listed" <|
            \_ ->
                let
                    input =
                        { types =
                            Dict.fromListBy QAST.typeDefinitionName
                                [ QAST.CustomTypeDef "Box"
                                    True
                                    emptyRange
                                    [ "a" ]
                                    [ ( "element", Type.Generic "b" ) ]
                                ]
                        , words =
                            Dict.empty
                        }
                            |> QualifierUtil.addFunctionsForStructs
                in
                case run input of
................................................................................
                        , Type.Custom "False"
                        ]

                template multiFn =
                    { types =
                        Dict.fromListBy QAST.typeDefinitionName
                            [ QAST.UnionTypeDef "Bool"
                                True
                                emptyRange
                                []
                                [ Type.Custom "True"
                                , Type.Custom "False"
                                ]
                            , QAST.CustomTypeDef "True" True emptyRange [] []
                            , QAST.CustomTypeDef "False" True emptyRange [] []
                            ]
                    , words =
                        Dict.fromListBy .name
                            [ multiFn
                            , { name = "main"
                              , metadata =
                                    Metadata.default
................................................................................
            , test "When returning union" <|
                \_ ->
                    let
                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Beings"
                                        True
                                        emptyRange
                                        []
                                        [ Type.Custom "Person"
                                        , Type.Custom "Dog"
                                        ]
                                    , QAST.CustomTypeDef "Person"
                                        True
                                        emptyRange
                                        []
                                        [ ( "age", Type.Int ) ]
                                    , QAST.CustomTypeDef "Dog"
                                        True
                                        emptyRange
                                        []
                                        [ ( "man-years", Type.Int ) ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "add-to-age"
................................................................................
            , test "Function requiring a concrete type should not accept an union with that type" <|
                \_ ->
                    let
                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Bool"
                                        True
                                        emptyRange
                                        []
                                        [ Type.Custom "True"
                                        , Type.Custom "False"
                                        ]
                                    , QAST.CustomTypeDef "True" True emptyRange [] []
                                    , QAST.CustomTypeDef "False" True emptyRange [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "not"
                                      , metadata = Metadata.default
                                      , implementation =
                                            QAST.MultiImpl
................................................................................
                                , Type.Custom "EmptyList"
                                ]

                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "List"
                                        True
                                        emptyRange
                                        [ "a" ]
                                        [ Type.CustomGeneric "NonEmptyList" [ Type.Generic "a" ]
                                        , Type.Custom "EmptyList"
                                        ]
                                    , QAST.CustomTypeDef "NonEmptyList"
                                        True
                                        emptyRange
                                        [ "a" ]
                                        [ ( "first", Type.Generic "a" )
                                        , ( "rest", listUnion )
                                        ]
                                    , QAST.CustomTypeDef "EmptyList"
                                        True
                                        emptyRange
                                        []
                                        []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "first-or-default"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
................................................................................
                                , Type.Custom "Nil"
                                ]

                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Maybe"
                                        True
                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nil"
                                        ]
                                    , QAST.CustomTypeDef "Nil"
                                        True
                                        emptyRange
                                        []
                                        []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "with-default"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
................................................................................
            , test "Generic union fails if not generic is listed" <|
                \_ ->
                    let
                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Maybe"
                                        True
                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "b"
                                        , Type.Custom "Nothing"
                                        ]
                                    , QAST.CustomTypeDef "Nothing"
                                        True
                                        emptyRange
                                        []
                                        []
                                    ]
                            , words =
                                Dict.empty
                            }
                                |> QualifierUtil.addFunctionsForStructs
                    in
                    case run input of
................................................................................
                                , Type.Custom "Nil"
                                ]

                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "Maybe"
                                        True
                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nil"
                                        ]
                                    , QAST.CustomTypeDef "Nil"
                                        True
                                        emptyRange
                                        []
                                        []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "map"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType
................................................................................
                                , Type.Custom "EmptyList"
                                ]

                        input =
                            { types =
                                Dict.fromListBy QAST.typeDefinitionName
                                    [ QAST.UnionTypeDef "List"
                                        True
                                        emptyRange
                                        [ "a" ]
                                        [ Type.CustomGeneric "NonEmptyList" [ Type.Generic "a" ]
                                        , Type.Custom "EmptyList"
                                        ]
                                    , QAST.CustomTypeDef "NonEmptyList"
                                        True
                                        emptyRange
                                        [ "a" ]
                                        [ ( "first", Type.Generic "a" )
                                        , ( "rest", listUnion )
                                        ]
                                    , QAST.CustomTypeDef "EmptyList"
                                        True
                                        emptyRange
                                        []
                                        []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "sum"
                                      , metadata = Metadata.default
                                      , implementation =
                                            QAST.SoloImpl

Modified tests/Test/TypeChecker/Error.elm from [59a5248785] to [8ad155b434].

19
20
21
22
23
24
25

26
27
28
29
30
31
32
..
84
85
86
87
88
89
90

91
92
93
94
95
96
97
...
174
175
176
177
178
179
180

181
182
183
184
185
186
187
188
189
190
191
192
193
194
...
342
343
344
345
346
347
348

349
350
351
352
353
354
355
...
516
517
518
519
520
521
522

523
524
525
526
527
528

529
530
531
532
533
534
535
536
537
538
539
        [ test "Undeclared generic" <|
            \_ ->
                let
                    ast =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ CustomTypeDef "Box"

                                    emptyRange
                                    [ "a" ]
                                    [ ( "value", Type.Generic "b" ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
................................................................................
        , test "Unexpected function" <|
            \_ ->
                let
                    ast =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ CustomTypeDef "IntBox"

                                    emptyRange
                                    []
                                    [ ( "value", Type.Int ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
................................................................................
        , test "An inferred union output type should not successfully type check against a generic variable" <|
            \_ ->
                let
                    ast =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef "Bool"

                                    emptyRange
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , CustomTypeDef "True" emptyRange [] []
                                , CustomTypeDef "False" emptyRange [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [] [ Type.Generic "out" ]
................................................................................
            , test "Nested" <|
                \_ ->
                    let
                        ast =
                            { types =
                                Dict.fromListBy typeDefinitionName
                                    [ CustomTypeDef "IntBox"

                                        emptyRange
                                        []
                                        [ ( "value", Type.Int ) ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "main"
................................................................................
                                , Type.Custom "Nil"
                                ]

                        input =
                            { types =
                                Dict.fromListBy typeDefinitionName
                                    [ UnionTypeDef "Maybe"

                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nil"
                                        ]
                                    , CustomTypeDef "IntBox"

                                        emptyRange
                                        []
                                        [ ( "value", Type.Int ) ]
                                    , CustomTypeDef "Nil" emptyRange [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = ">Nil"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType [] [ Type.Custom "Nil" ]







>







 







>







 







>





|
|







 







>







 







>






>



|







19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
..
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
...
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
...
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
...
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
        [ test "Undeclared generic" <|
            \_ ->
                let
                    ast =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ CustomTypeDef "Box"
                                    False
                                    emptyRange
                                    [ "a" ]
                                    [ ( "value", Type.Generic "b" ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
................................................................................
        , test "Unexpected function" <|
            \_ ->
                let
                    ast =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ CustomTypeDef "IntBox"
                                    False
                                    emptyRange
                                    []
                                    [ ( "value", Type.Int ) ]
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
................................................................................
        , test "An inferred union output type should not successfully type check against a generic variable" <|
            \_ ->
                let
                    ast =
                        { types =
                            Dict.fromListBy typeDefinitionName
                                [ UnionTypeDef "Bool"
                                    False
                                    emptyRange
                                    []
                                    [ Type.Custom "True"
                                    , Type.Custom "False"
                                    ]
                                , CustomTypeDef "True" False emptyRange [] []
                                , CustomTypeDef "False" False emptyRange [] []
                                ]
                        , words =
                            Dict.fromListBy .name
                                [ { name = "main"
                                  , metadata =
                                        Metadata.default
                                            |> Metadata.withType [] [ Type.Generic "out" ]
................................................................................
            , test "Nested" <|
                \_ ->
                    let
                        ast =
                            { types =
                                Dict.fromListBy typeDefinitionName
                                    [ CustomTypeDef "IntBox"
                                        False
                                        emptyRange
                                        []
                                        [ ( "value", Type.Int ) ]
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "main"
................................................................................
                                , Type.Custom "Nil"
                                ]

                        input =
                            { types =
                                Dict.fromListBy typeDefinitionName
                                    [ UnionTypeDef "Maybe"
                                        False
                                        emptyRange
                                        [ "a" ]
                                        [ Type.Generic "a"
                                        , Type.Custom "Nil"
                                        ]
                                    , CustomTypeDef "IntBox"
                                        False
                                        emptyRange
                                        []
                                        [ ( "value", Type.Int ) ]
                                    , CustomTypeDef "Nil" False emptyRange [] []
                                    ]
                            , words =
                                Dict.fromListBy .name
                                    [ { name = ">Nil"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.withType [] [ Type.Custom "Nil" ]

Modified wasm_tests/basics.test.js from [981cd381d2] to [aa9864714d].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const compiler = require('./compiler.wrapper');

test('Simple expression', async () => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        : 1 1 +
    `);

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

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

test('Function calls', async () => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        : 1 inc inc

        def: inc
        : 1 +
    `);

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

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



|

<









|

<










1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24
25
26
const compiler = require('./compiler.wrapper');

test('Simple expression', async () => {
    const wat = await compiler.toWat('main', `
        def: main

        : 1 1 +
    `);

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

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

test('Function calls', async () => {
    const wat = await compiler.toWat('main', `
        def: main

        : 1 inc inc

        def: inc
        : 1 +
    `);

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

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

Modified wasm_tests/compiler.wrapper.js from [527dbd0b5f] to [f024764ef8].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const Compiler = require('./compiler.js');
const wabtInit = require('wabt');
const stripIndent = require('strip-indent');

exports.toWat = function toWat(sourceCode) {
    return new Promise((resolve, reject) => {
        const compiler = Compiler.Elm.Main.init({});

        compiler.ports.compileFinished.subscribe(([ok, output]) => {
            if (ok) {
                resolve(output);
            } else {
                reject(output);
            }
        });

        compiler.ports.compileString.send(stripIndent(sourceCode));
    });
}

exports.run = async function run(wat, functionName) {
    const wabt = await wabtInit();
    const wasmModule = wabt.parseWat('tmp', wat).toBinary({}).buffer;





|

|









|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const Compiler = require('./compiler.js');
const wabtInit = require('wabt');
const stripIndent = require('strip-indent');

exports.toWat = function toWat(entry, sourceCode) {
    return new Promise((resolve, reject) => {
        const compiler = Compiler.Elm.TestCompiler.init({});

        compiler.ports.compileFinished.subscribe(([ok, output]) => {
            if (ok) {
                resolve(output);
            } else {
                reject(output);
            }
        });

        compiler.ports.compileString.send([entry, stripIndent(sourceCode)]);
    });
}

exports.run = async function run(wat, functionName) {
    const wabt = await wabtInit();
    const wasmModule = wabt.parseWat('tmp', wat).toBinary({}).buffer;

Modified wasm_tests/math.test.js from [3440282ac4] to [b8ebd73e94].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const compiler = require('./compiler.wrapper');

test('Addition', async () => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        : 3 3 +
    `);

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

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

test('Subtraction', async () => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        : 10 1 -
    `);

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

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

test('Multiplication', async () => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        : 5 3 *
    `);

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

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

test('Division', async () => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        : 10 5 div
    `);

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

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



|

<









|

<









|

<









|

<







1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24
25
26
27

28
29
30
31
32
33
34
35
36
37
38

39
40
41
42
43
44
45
const compiler = require('./compiler.wrapper');

test('Addition', async () => {
    const wat = await compiler.toWat('main', `
        def: main

        : 3 3 +
    `);

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

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

test('Subtraction', async () => {
    const wat = await compiler.toWat('main', `
        def: main

        : 10 1 -
    `);

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

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

test('Multiplication', async () => {
    const wat = await compiler.toWat('main', `
        def: main

        : 5 3 *
    `);

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

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

test('Division', async () => {
    const wat = await compiler.toWat('main', `
        def: main

        : 10 5 div
    `);

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

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

Modified wasm_tests/multiword.test.js from [aadc36f12d] to [2577567c39].

1
2
3
4
5
6
7
8
9
10
11
..
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
..
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
...
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
...
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
const compiler = require('./compiler.wrapper');

test('Simple case', async () => {
    const wat = await compiler.toWat(`
        defunion: Bool
        : True
        : False

        defstruct: True
        defstruct: False

................................................................................
        defmulti: to-int
        : True
          drop 100
        : False
          drop 75

        def: main
        entry: true
        : True to-int 
          False to-int 
          -
    `);

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

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

// Same as above, but without an explicit False branch.
test('Default branch', async () => {
    const wat = await compiler.toWat(`
        defunion: Bool
        : True 
        : False

        defstruct: True
        defstruct: False

        defmulti: to-int
        : True
          drop 100
        else: drop 75

        def: main
        entry: true
        : True to-int 
          False to-int 
          -
    `);

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

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

test('Multiple arguments', async () => {
    const wat = await compiler.toWat(`
        defunion: Beings
        : Person 
        : Dog

        defstruct: Person
        : age Int

................................................................................
        defmulti: get-man-age
        : Person
          age>
        : Dog
          man-years>

        def: main
        entry: true
        : 18 >Person 10 add-to-age 
          0 >Dog 2 add-to-age 
          get-man-age swap 
          get-man-age swap 
          -
    `);

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

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

test('Generic arguments', async () => {
    const wat = await compiler.toWat(`
        defunion: List a
        : NonEmptyList a 
        : EmptyList

        defstruct: NonEmptyList a
        : first a
        : rest List a
................................................................................
        defmulti: first-or-default
        : NonEmptyList
          drop first>
        : EmptyList
          swap drop

        def: main
        entry: true
        : 1 EmptyList >NonEmptyList
          0 first-or-default
    `);

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

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

test('Recursive word', async () => {
    const wat = await compiler.toWat(`
        defunion: List a
        : NonEmptyList a 
        : EmptyList

        defstruct: NonEmptyList a
        : first a
        : rest List a
................................................................................
        type: (List a) Int -- Int
        : NonEmptyList
          swap dup first> rotate rest> rotate + sum-helper
        : EmptyList
          swap drop

        def: main
        entry: true
        : 1 2 3 EmptyList >NonEmptyList >NonEmptyList >NonEmptyList
          sum
    `);

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

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

test('Int case', async () => {
    const wat = await compiler.toWat(`
        defunion: IntParseResult
        : Int
        : NoInt

        defstruct: NoInt

        defmulti: double
        : Int
          2 *
        : NoInt
          drop 0

        def: main
        entry: true
        : 4 double
    `);

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

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

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

        def: main
        entry: true
        : 0 double
    `);

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

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

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

        def: main
        entry: true
        : 6 double
    `);

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

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

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

        def: main
        entry: true
        : 10 6 add
    `);

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

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

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

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

        def: main
        entry: true
        : 0 Nil inc-zero
          drop 
    `);

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

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

test('Generic case', async () => {
    const wat = await compiler.toWat(`
        defunion: Maybe a
        : a
        : Nil

        defstruct: Nil

        defmulti: map
................................................................................
        type: (Maybe a) a -- a
        : a
          drop
        : Nil
          swap drop

        def: main
        entry: true
        : 10
          [ 1 - ] map
          0 with-default
    `);

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

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



|







 







<












|













<











|







 







<













|







 







<










|







 







<










|













<









|







<









|







<









|










<









|










<










|







 







<









1
2
3
4
5
6
7
8
9
10
11
..
12
13
14
15
16
17
18

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
78
79
80
81
82
83
84

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
...
109
110
111
112
113
114
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
...
141
142
143
144
145
146
147

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171

172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205

206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
...
271
272
273
274
275
276
277

278
279
280
281
282
283
284
285
286
const compiler = require('./compiler.wrapper');

test('Simple case', async () => {
    const wat = await compiler.toWat('main', `
        defunion: Bool
        : True
        : False

        defstruct: True
        defstruct: False

................................................................................
        defmulti: to-int
        : True
          drop 100
        : False
          drop 75

        def: main

        : True to-int 
          False to-int 
          -
    `);

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

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

// Same as above, but without an explicit False branch.
test('Default branch', async () => {
    const wat = await compiler.toWat('main', `
        defunion: Bool
        : True 
        : False

        defstruct: True
        defstruct: False

        defmulti: to-int
        : True
          drop 100
        else: drop 75

        def: main

        : True to-int 
          False to-int 
          -
    `);

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

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

test('Multiple arguments', async () => {
    const wat = await compiler.toWat('main', `
        defunion: Beings
        : Person 
        : Dog

        defstruct: Person
        : age Int

................................................................................
        defmulti: get-man-age
        : Person
          age>
        : Dog
          man-years>

        def: main

        : 18 >Person 10 add-to-age 
          0 >Dog 2 add-to-age 
          get-man-age swap 
          get-man-age swap 
          -
    `);

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

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

test('Generic arguments', async () => {
    const wat = await compiler.toWat('main', `
        defunion: List a
        : NonEmptyList a 
        : EmptyList

        defstruct: NonEmptyList a
        : first a
        : rest List a
................................................................................
        defmulti: first-or-default
        : NonEmptyList
          drop first>
        : EmptyList
          swap drop

        def: main

        : 1 EmptyList >NonEmptyList
          0 first-or-default
    `);

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

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

test('Recursive word', async () => {
    const wat = await compiler.toWat('main', `
        defunion: List a
        : NonEmptyList a 
        : EmptyList

        defstruct: NonEmptyList a
        : first a
        : rest List a
................................................................................
        type: (List a) Int -- Int
        : NonEmptyList
          swap dup first> rotate rest> rotate + sum-helper
        : EmptyList
          swap drop

        def: main

        : 1 2 3 EmptyList >NonEmptyList >NonEmptyList >NonEmptyList
          sum
    `);

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

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

test('Int case', async () => {
    const wat = await compiler.toWat('main', `
        defunion: IntParseResult
        : Int
        : NoInt

        defstruct: NoInt

        defmulti: double
        : Int
          2 *
        : NoInt
          drop 0

        def: main

        : 4 double
    `);

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

    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
    `);

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

    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
    `);

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

    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
          +

        def: main

        : 10 6 add
    `);

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

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

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
          drop 
    `);

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

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

test('Generic case', async () => {
    const wat = await compiler.toWat('main', `
        defunion: Maybe a
        : a
        : Nil

        defstruct: Nil

        defmulti: map
................................................................................
        type: (Maybe a) a -- a
        : a
          drop
        : Nil
          swap drop

        def: main

        : 10
          [ 1 - ] map
          0 with-default
    `);

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

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

Modified wasm_tests/pattern_match.test.js from [72e613569d] to [57e7981f91].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65




















66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
const compiler = require('./compiler.wrapper');

test('Basic pattern match', async () => {
    const wat = await compiler.toWat(`
        defstruct: Box
        : value Int

        defmulti: not
        : Box( value 0 )
          drop 1
        : Box
          drop 0

        def: main
        entry: true
        : 0 >Box not
    `);

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

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

test('Basic pattern match with default implementation', async () => {
    const wat = await compiler.toWat(`
        defstruct: Box
        : value Int

        defmulti: not
        : Box( value 0 )
          drop 1
        else: drop 0

        def: main
        entry: true
        : 0 >Box not
    `);

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

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

test('Basic pattern match reverse case', async () => {
    const wat = await compiler.toWat(`
        defstruct: Box
        : value Int

        defmulti: not
        : Box( value 0 )
          drop 1
        else: drop 0

        def: main
        entry: true
        : 1 >Box not
    `);

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

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

test('Multiple arguments', async () => {
    const wat = await compiler.toWat(`




















        defstruct: Point
        : first Int
        : second Int

        defmulti: origo?
        : Point( first 0 second 0 )
          drop 1
        else: drop 0

        def: main
        entry: true
        : 0 0 >Point origo?
    `);

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

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

test('Multiple arguments reverse case', async () => {
    const wat = await compiler.toWat(`
        defstruct: Point
        : first Int
        : second Int

        defmulti: origo?
        : Point( first 0 second 0 )
          drop 1
        else: drop 0

        def: main
        entry: true
        : 0 1 >Point origo?
    `);

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

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

test('Recursive match', async () => {
    const wat = await compiler.toWat(`
        defstruct: Box
        : value Int

        defstruct: BoxOfBox
        : box Box

        defmulti: deep-one?
        : BoxOfBox( box Box( value 1 ) )
          drop 1
        else: drop 0

        def: main
        entry: true
        : 1 >Box >BoxOfBox deep-one?
    `);

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

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

test('Recursive match reverse case', async () => {
    const wat = await compiler.toWat(`
        defstruct: Box
        : value Int

        defstruct: BoxOfBox
        : box Box

        defmulti: deep-one?
        : BoxOfBox( box Box( value 1 ) )
          drop 1
        else: drop 0

        def: main
        entry: true
        : 2 >Box >BoxOfBox deep-one?
    `);

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

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



|










<









|









<









|









<









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










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









|












<









|












<







1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92






















93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136

137
138
139
140
141
142
143
const compiler = require('./compiler.wrapper');

test('Basic pattern match', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Box
        : value Int

        defmulti: not
        : Box( value 0 )
          drop 1
        : Box
          drop 0

        def: main

        : 0 >Box not
    `);

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

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

test('Basic pattern match with default implementation', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Box
        : value Int

        defmulti: not
        : Box( value 0 )
          drop 1
        else: drop 0

        def: main

        : 0 >Box not
    `);

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

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

test('Basic pattern match reverse case', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Box
        : value Int

        defmulti: not
        : Box( value 0 )
          drop 1
        else: drop 0

        def: main

        : 1 >Box not
    `);

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

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

test('Multiple arguments', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Point
        : first Int
        : second Int

        defmulti: origo?
        : Point( first 0 second 0 )
          drop 1
        else: drop 0

        def: main
        : 0 0 >Point origo?
    `);

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

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

test('Multiple arguments reverse case', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Point
        : first Int
        : second Int

        defmulti: origo?
        : Point( first 0 second 0 )
          drop 1
        else: drop 0

        def: main






















        : 0 1 >Point origo?
    `);

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

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

test('Recursive match', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Box
        : value Int

        defstruct: BoxOfBox
        : box Box

        defmulti: deep-one?
        : BoxOfBox( box Box( value 1 ) )
          drop 1
        else: drop 0

        def: main

        : 1 >Box >BoxOfBox deep-one?
    `);

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

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

test('Recursive match reverse case', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Box
        : value Int

        defstruct: BoxOfBox
        : box Box

        defmulti: deep-one?
        : BoxOfBox( box Box( value 1 ) )
          drop 1
        else: drop 0

        def: main

        : 2 >Box >BoxOfBox deep-one?
    `);

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

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

Modified wasm_tests/quotes.test.js from [8233315f50] to [97846aa4b6].

1
2
3
4
5
6
7
8
9
10
11
12
13
..
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const compiler = require('./compiler.wrapper');

test('Basic quotation', async () => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        : 2 [ inc dec dec ] !

        def: inc
        : 1 +

        def: dec
        : 1 -
................................................................................

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

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

test('Basic quotation', async () => {
    const wat = await compiler.toWat(`
        defstruct: Coordinate
        : x Int
        : y Int

        def: update-x
        type: Coordinate [ Int -- Int ] -- Coordinate
        : swap
          dup x>
          -rotate
          !
          >x

        def: main
        entry: true
        : 1 2 >Coordinate
          [ 1 + ] update-x
          x>
    `);

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

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



|

<







 







|













<









1
2
3
4
5

6
7
8
9
10
11
12
..
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

35
36
37
38
39
40
41
42
43
const compiler = require('./compiler.wrapper');

test('Basic quotation', async () => {
    const wat = await compiler.toWat('main', `
        def: main

        : 2 [ inc dec dec ] !

        def: inc
        : 1 +

        def: dec
        : 1 -
................................................................................

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

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

test('Basic quotation', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Coordinate
        : x Int
        : y Int

        def: update-x
        type: Coordinate [ Int -- Int ] -- Coordinate
        : swap
          dup x>
          -rotate
          !
          >x

        def: main

        : 1 2 >Coordinate
          [ 1 + ] update-x
          x>
    `);

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

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

Modified wasm_tests/record.test.js from [203aebee22] to [6889e1e1fa].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const compiler = require('./compiler.wrapper');

test('Enum type', async () => {
    const wat = await compiler.toWat(`
       defstruct: True 
       defstruct: False

       def: main
       entry: true
       : True
    `);

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

    // types are sorted alphabetically, so False will get id 0, and True gets id 1.
    expect(result.typeIdForPointer()).toBe(1);
});

test('Compound type', async () => {
    const wat = await compiler.toWat(`
        defstruct: Person
        : age Int

        def: inc-age
        : age> 1 + >Person

        def: main
        entry: true
        : 1 >Person 19 >age inc-age age>
    `);

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

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



|




<










|







<







1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

27
28
29
30
31
32
33
const compiler = require('./compiler.wrapper');

test('Enum type', async () => {
    const wat = await compiler.toWat('main', `
       defstruct: True 
       defstruct: False

       def: main

       : True
    `);

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

    // types are sorted alphabetically, so False will get id 0, and True gets id 1.
    expect(result.typeIdForPointer()).toBe(1);
});

test('Compound type', async () => {
    const wat = await compiler.toWat('main', `
        defstruct: Person
        : age Int

        def: inc-age
        : age> 1 + >Person

        def: main

        : 1 >Person 19 >age inc-age age>
    `);

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

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

Modified wasm_tests/stack.test.js from [493c219118] to [ba1b453211].

1
2
3
4
5
6
7
8
9
10
11
12
13
..
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
..
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const compiler = require('./compiler.wrapper');

test('Square', async () => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        type: -- Int
        : 5 square

        def: square
        type: Int -- Int
        : dup *
    `);
................................................................................

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

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

test('Over', async() => {
    const wat = await compiler.toWat(`
        def: main
        entry: true
        type: -- Int
        : 1 2 over - + 2 =

        def: over
        type: a b -- a b a
        : swap dup rotate
    `);
................................................................................

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

test('Under', async() => {
    // Not sure if under is actually a known function in forth
    // This is mainly to test -rotate
    const wat = await compiler.toWat(`
        def: main
        entry: true
        type: -- Int
        : 1 2 under - + 3 =

        def: under
        type: a b -- b b a
        : dup -rotate
    `);

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

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



|

<







 







|

<







 







|

<












1
2
3
4
5

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

22
23
24
25
26
27
28
..
31
32
33
34
35
36
37
38
39

40
41
42
43
44
45
46
47
48
49
50
51
const compiler = require('./compiler.wrapper');

test('Square', async () => {
    const wat = await compiler.toWat('main', `
        def: main

        type: -- Int
        : 5 square

        def: square
        type: Int -- Int
        : dup *
    `);
................................................................................

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

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

test('Over', async() => {
    const wat = await compiler.toWat('main', `
        def: main

        type: -- Int
        : 1 2 over - + 2 =

        def: over
        type: a b -- a b a
        : swap dup rotate
    `);
................................................................................

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

test('Under', async() => {
    // Not sure if under is actually a known function in forth
    // This is mainly to test -rotate
    const wat = await compiler.toWat('main', `
        def: main

        type: -- Int
        : 1 2 under - + 3 =

        def: under
        type: a b -- b b a
        : dup -rotate
    `);

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

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