Play

Check-in [9318fc4c3b]
Login
Overview
Comment:Add cli program to compile projects, run functions and initiate new projects.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: 9318fc4c3b5ff89c307998f8496c0d993069b1c30574bbbf71024eccfd2595c9
User & Date: robin.hansen on 2021-04-07 13:39:26
Other Links: manifest | tags
Context
2021-04-17
11:05
First implementation of the standard library. Leaf check-in: 7e9c8cf531 user: robin.hansen tags: trunk
2021-04-07
14:32
Begin working on a proper standard_library. check-in: 7c2806c6fc user: robin.hansen tags: stdlib
13:39
Add cli program to compile projects, run functions and initiate new projects. check-in: 9318fc4c3b user: robin.hansen tags: trunk
13:38
CLI now injects path to stdlib as a package path. Closed-Leaf check-in: 40164ce609 user: robin.hansen tags: cli
2021-03-30
09:41
Fix compile error in Main.elm check-in: d20a4dc6a5 user: robin.hansen tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added bin/cli.js version [30c9406240].















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/env node

const path = require("path");
const fs = require("fs");
const wabtInit = require("wabt");

const stdLibPath = path.resolve(__dirname, "..", "stdlib");
const cwd = process.cwd();

const subCmd = process.argv[2];
const subCmdFlags = process.argv.slice(3);

switch (subCmd) {
    case "init": initProject(); break;
    case "run": runProject(); break;
    case "compile": compileProject(); break;
    default: printHelp(); break;
}

function initProject() {
    if (subCmdFlags.length !== 1) {
        console.error("'init' requires exactly one argument: the package name.");
        return;
    }

    fs.mkdirSync(path.join(cwd, "src"));

    const playJson = {
        name: subCmdFlags[0],
        version: "0.1.0",
        "language-version": "0.2.0",
        "exposed-modules": [
            "main"
        ],
        dependencies: {
            "play/standard_library": "0.2.0"
        },
        "package-paths": []
    };

    fs.writeFileSync(path.join(cwd, "play.json"), JSON.stringify(playJson, null, 4));

    fs.writeFileSync(path.join(cwd, "src", "main.play"), `
def: execute
: 0
`.trim());
}

function runProject() {
    if (subCmdFlags.length !== 1) {
        console.error("'run' requires exactly one argument: the function to run.");
        return;
    }

    compileProject(subCmdFlags[0]);
}

function compileProject(entryPoint) {
    const rootJsonMetaPath = path.join(cwd, "play.json");
    if (!fs.existsSync(rootJsonMetaPath)) {
        console.error("No 'play.json' file found in this directory.");
        return;
    }

    const compiler = require(__dirname + "/compiler").Elm.CLI.init({
        flags: {
            projectDir: cwd,
            entryPoint: typeof entryPoint === "undefined" ? null : entryPoint,
            stdLibPath: stdLibPath
        }
    });

    compiler.ports.outgoingPort.subscribe((msg) => {
        switch (msg.type) {
            case 'readFile':
                const filePath = path.join(msg.path, msg.fileName);
                const fileContent = fs.readFileSync(filePath, { encoding: "utf-8" });

                compiler.ports.incomingPort.send({
                    type: "fileContents",
                    path: msg.path,
                    fileName: msg.fileName,
                    content: fileContent
                });
                break;
            case "resolvePackageModules":
                const srcPath = path.join(msg.path, "src");
                const childrenFiles = expandDir(msg.path)("src")
                    .filter(name => name.endsWith(".play"))
                    .map(name => name.replace(srcPath + "/", ""));

                compiler.ports.incomingPort.send({
                    type: "resolvedPackageModules",
                    package: msg.package,
                    modules: childrenFiles
                });
                break;
            case "resolveDirectories":
                const subFolders = packageDirs(msg.path);

                compiler.ports.incomingPort.send({
                    type: "resolvedDirectories",
                    parentDir: msg.path,
                    paths: subFolders
                });
                break;
            case "compilationDone":
                if (typeof entryPoint === "undefined") {
                    console.log("Compiled successfully");
                } else {
                    executeWat(msg.wast, entryPoint);
                }
                break;
            case "compilationFailure":
                console.error(msg.error);
                break;
            default:
                console.error("Unknown message received from Elm compiler: ", msg);
                break;
        }
    });
}

function expandDir(basePath) {
    return (dirPath) => {
        const srcPath = path.join(basePath, dirPath);

        if (fs.statSync(srcPath).isFile()) {
            return srcPath;
        }

        const children = fs.readdirSync(srcPath);
        return children.flatMap(expandDir(srcPath));
    };
}

function packageDirs(parentDir) {
    return fs.readdirSync(parentDir)
        .map(dir => path.join(parentDir, dir))
        .filter(dir => fs.statSync(dir).isDirectory())
        .filter(dir => fs.readdirSync(dir).indexOf('play.json') >= 0);
}

function printHelp() {
    console.log(`
Play compiler. Alpha-2.

Possible options are:
* init <package_name>: initialize a new project in the current directory.
* compile: compile the project.
* run <function_name>: compile the project and execute the given function.
* help: print this help message.
    `);
}

async function executeWat(wat, entryPointName) {
    const wabt = await wabtInit();
    const wasmModule = wabt.parseWat('tmp', wat).toBinary({}).buffer;

    const memory = new WebAssembly.Memory({
        initial: 10
    });

    const imports = {
        host: {
            memory: memory
        }
    };

    const program = await WebAssembly.instantiate(wasmModule, imports);
    const entryPoint = program.instance.exports[entryPointName];
    if (typeof entryPoint === 'undefined') {
        console.error("Could not find a function named '" + entryPointName + "'");
        return;
    }

    entryPoint();

    const memView = new Int32Array(memory.buffer);
    // First three i32 elements are stack and heap information
    const returnValue = memView[3].toString(); 
    console.log(returnValue);
}

Modified package.json from [ad181fde73] to [895cd12b4c].

1
2
3
4


5
6
7
8
9
10
11
12
13
14
15
16
17
18

19
20
21

22

{
  "name": "play",
  "version": "0.0.1",
  "description": "",


  "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"

  },
  "author": "Robin Heggelund Hansen",
  "license": "MIT"

}





>
>













|
>

<
|
>
|
>
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
{
  "name": "play",
  "version": "0.0.1",
  "description": "",
  "author": "Robin Heggelund Hansen",
  "license": "MIT",
  "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"
  }
}

Added src/CLI.elm version [2a2a2f3219].

































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
port module CLI exposing (main)

import Json.Decode as Json
import Json.Encode as Encode
import Platform exposing (Program)
import Play.Codegen as Codegen
import Play.Data.PackagePath as PackagePath
import Play.PackageLoader as PackageLoader
import Play.TypeChecker as TypeChecker
import Play.TypeChecker.Problem as TypeCheckerProblem
import Wasm


type alias Flags =
    { projectDir : String
    , entryPoint : Maybe String
    , stdLibPath : String
    }


type alias Model =
    PackageLoader.Model


type Msg
    = Incomming Json.Value


main : Program Flags Model Msg
main =
    Platform.worker
        { init = init
        , update = update
        , subscriptions = subscriptions
        }


init : Flags -> ( Model, Cmd Msg )
init { projectDir, entryPoint, stdLibPath } =
    let
        initialModel =
            PackageLoader.init
                { projectDirPath = projectDir
                , possibleEntryPoint = entryPoint
                , stdLibPath = stdLibPath
                }
    in
    ( initialModel
    , sendSideEffectFromModel initialModel
    )


sendSideEffectFromModel : PackageLoader.Model -> Cmd Msg
sendSideEffectFromModel model =
    PackageLoader.getSideEffect model
        |> Maybe.map encodeSideEffectAsJson
        |> Maybe.map outgoingPort
        |> Maybe.withDefault Cmd.none


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Incomming packageLoaderMsgJson ->
            case Json.decodeValue decodePackageLoaderMsg packageLoaderMsgJson of
                Ok packageLoaderMsg ->
                    let
                        updatedModel =
                            PackageLoader.update packageLoaderMsg model
                    in
                    case updatedModel of
                        PackageLoader.Done qualifiedAst ->
                            let
                                compilationResult =
                                    case TypeChecker.run qualifiedAst of
                                        Err typeErrors ->
                                            formatErrors (TypeCheckerProblem.toString "") typeErrors

                                        Ok typedAst ->
                                            Codegen.codegen typedAst
                                                |> Result.mapError (always "compfail")
                                                |> Result.map Wasm.toString
                            in
                            case compilationResult of
                                Ok wast ->
                                    ( model
                                    , outgoingPort <| encodeCompilationDone wast
                                    )

                                Err error ->
                                    ( model
                                    , outgoingPort <| encodeCompilationFailure error
                                    )

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

                        _ ->
                            ( updatedModel
                            , sendSideEffectFromModel updatedModel
                            )

                Err decodeError ->
                    ( model
                    , outgoingPort <|
                        encodeCompilationFailure <|
                            Json.errorToString decodeError
                    )


formatErrors : (a -> String) -> List a -> Result String b
formatErrors fn problems =
    problems
        |> List.map fn
        |> String.join "\n\n"
        |> Err



-- Json Encoding/Decoding


encodeSideEffectAsJson : PackageLoader.SideEffect -> Json.Value
encodeSideEffectAsJson sf =
    case sf of
        PackageLoader.ReadFile path fileName ->
            Encode.object
                [ ( "type", Encode.string "readFile" )
                , ( "path", Encode.string path )
                , ( "fileName", Encode.string fileName )
                ]

        PackageLoader.ResolveDirectories path ->
            Encode.object
                [ ( "type", Encode.string "resolveDirectories" )
                , ( "path", Encode.string path )
                ]

        PackageLoader.ResolvePackageModules moduleName path ->
            Encode.object
                [ ( "type", Encode.string "resolvePackageModules" )
                , ( "package", Encode.string moduleName )
                , ( "path", Encode.string path )
                ]


encodeCompilationDone : String -> Json.Value
encodeCompilationDone wast =
    Encode.object
        [ ( "type", Encode.string "compilationDone" )
        , ( "wast", Encode.string wast )
        ]


encodeCompilationFailure : String -> Json.Value
encodeCompilationFailure errorMsg =
    Encode.object
        [ ( "type", Encode.string "compilationFailure" )
        , ( "error", Encode.string errorMsg )
        ]


decodePackageLoaderMsg : Json.Decoder PackageLoader.Msg
decodePackageLoaderMsg =
    let
        helper typeStr =
            case typeStr of
                "fileContents" ->
                    Json.map3 PackageLoader.FileContents
                        (Json.field "path" Json.string)
                        (Json.field "fileName" Json.string)
                        (Json.field "content" Json.string)

                "resolvedPackageModules" ->
                    Json.map2 PackageLoader.ResolvedPackageModules
                        (Json.field "package" Json.string)
                        (Json.field "modules" (Json.list Json.string))

                "resolvedDirectories" ->
                    Json.map2 PackageLoader.ResolvedDirectories
                        (Json.field "parentDir" Json.string)
                        (Json.field "paths" (Json.list packagePathDecoder))

                _ ->
                    Json.fail <| "Unknown msg type: " ++ typeStr

        packagePathDecoder =
            Json.map PackagePath.fromString Json.string
    in
    Json.field "type" Json.string
        |> Json.andThen helper



-- PORTS


subscriptions : Model -> Sub Msg
subscriptions _ =
    incomingPort Incomming


port incomingPort : (Json.Value -> msg) -> Sub msg


port outgoingPort : Json.Value -> Cmd msg

Modified src/Play/Data/PackagePath.elm from [b58e74fd1c] to [1e9585ddbd].

36
37
38
39
40
41
42




43
44
45




46
    ctor <| String.dropRight charsToDrop str


prefix : String -> PackagePath -> PackagePath
prefix pathToPrefix packagePath =
    case packagePath of
        Directory dir ->




            Directory <| pathToPrefix ++ "/" ++ dir

        AllDirectoriesInDirectory dir ->




            AllDirectoriesInDirectory <| pathToPrefix ++ "/" ++ dir







>
>
>
>
|


>
>
>
>
|
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    ctor <| String.dropRight charsToDrop str


prefix : String -> PackagePath -> PackagePath
prefix pathToPrefix packagePath =
    case packagePath of
        Directory dir ->
            if String.startsWith "/" dir then
                packagePath

            else
                Directory <| pathToPrefix ++ "/" ++ dir

        AllDirectoriesInDirectory dir ->
            if String.startsWith "/" dir then
                packagePath

            else
                AllDirectoriesInDirectory <| pathToPrefix ++ "/" ++ dir

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

1
2
3
4
5

6
7
8
9
10
11
12

13
14
15
16
17
18
19
..
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
..
53
54
55
56
57
58
59
60
61

62
63
64
65
66
67
68
69
..
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
...
470
471
472
473
474
475
476



















477
478
479

480
481
482
483
484
485
486
module Play.PackageLoader exposing
    ( Model(..)
    , Msg(..)
    , Problem(..)
    , SideEffect(..)

    , init
    , update
    )

import Dict exposing (Dict)
import Json.Decode as Json
import List.Extra as List

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
................................................................................
type Problem
    = InvalidPackageMetadata String String
    | UnknownMessageForState String
    | NoExposedModulesInRootProject
    | ModuleNotFound String
    | InternalError String









type Model
    = Initializing 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 =

    { 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 : PackageInfo -> State
emptyState rootPackage =

    { rootPackage = rootPackage
    , dependencies = rootPackage.metadata.dependencies
    , dependentPackages = Dict.empty
    , filePathToModule = Dict.empty
    , moduleNameToPackageName = Dict.empty
    , absoluteModuleNameToDetails = Dict.empty
    , inProgressAst = Nothing
    , parsedModules = Set.empty
................................................................................

type SideEffect
    = ReadFile String String
    | ResolveDirectories String
    | ResolvePackageModules String String


init : String -> Model
init projectDirPath =







    Initializing















        (ReadFile projectDirPath "play.json")


update : Msg -> Model -> Model
update msg model =
    case model of
        Initializing _ ->
            case msg of
                FileContents path _ content ->
                    case Json.decodeString PackageMetadata.decoder content of
                        Ok metadata ->
                            let






                                state =
                                    emptyState
                                        { path = path
                                        , metadata = metadata
                                        , modules = []
                                        }

                                pathsToLoad =
                                    List.map (PackagePath.prefix path) metadata.packagePaths
                            in
                            case pathsToLoad of
                                [] ->
                                    ResolvingModulePaths state [] <|
                                        ResolvePackageModules (PackageName.toString metadata.name) path

                                (PackagePath.Directory nextPathDir) :: _ ->
................................................................................
    "/" ++ PackageName.toString packageName ++ "/" ++ ModuleName.toString moduleName


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



















            Done
                { types = inProgressAst.types
                , words = inProgressAst.words

                }

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





>







>







 








>
>
>
>
>
>
>

|








>
|







 







|
|
>
|







 







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





|





>
>
>
>
>
>

|

|




|







 







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


<
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
..
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
..
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
..
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
...
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
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
................................................................................
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 SideEffect
    = ReadFile String String
    | ResolveDirectories String
    | ResolvePackageModules String String


getSideEffect : Model -> Maybe SideEffect
getSideEffect model =
    case model of
        Done _ ->
            Nothing

        Failed _ ->
            Nothing

        Initializing _ sf ->
            Just sf

        LoadingMetadata _ _ sf ->
            Just sf

        ResolvingModulePaths _ _ sf ->
            Just sf

        Compiling _ _ sf ->
            Just sf


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


update : Msg -> Model -> Model
update msg model =
    case model of
        Initializing initOpts _ ->
            case msg of
                FileContents path _ content ->
                    case Json.decodeString PackageMetadata.decoder content of
                        Ok metadata ->
                            let
                                metadataWithStdLib =
                                    { metadata
                                        | packagePaths =
                                            metadata.packagePaths ++ [ PackagePath.fromString initOpts.stdLibPath ]
                                    }

                                state =
                                    emptyState initOpts
                                        { path = path
                                        , metadata = metadataWithStdLib
                                        , modules = []
                                        }

                                pathsToLoad =
                                    List.map (PackagePath.prefix path) metadataWithStdLib.packagePaths
                            in
                            case pathsToLoad of
                                [] ->
                                    ResolvingModulePaths state [] <|
                                        ResolvePackageModules (PackageName.toString metadata.name) path

                                (PackagePath.Directory nextPathDir) :: _ ->
................................................................................
    "/" ++ 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

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

175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
...
230
231
232
233
234
235
236

237
238
239
240
241
242
243
        }
        |. Parser.oneOf
            [ Parser.succeed identity
                |. Parser.symbol (Token ":" NotMetadata)
                |> Parser.andThen (\_ -> Parser.problem FoundMetadata)
            , Parser.succeed identity
            ]
        |. noiseParser
        |> Parser.backtrackable


symbolImplParser2 : Parser (SourceLocationRange -> AstNode)
symbolImplParser2 =
    let
        externalBuilder firstSymbol (( partialPath, reference ) as modulePathResult) =
................................................................................
        , Parser.succeed internalBuilder
            |= symbolImplParser
            |= Parser.oneOf
                [ Parser.loop [] modulePathParser
                , Parser.succeed ( [], "" )
                ]
        ]

        |> 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))







<







 







>







175
176
177
178
179
180
181

182
183
184
185
186
187
188
...
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
        }
        |. Parser.oneOf
            [ 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) =
................................................................................
        , Parser.succeed internalBuilder
            |= symbolImplParser
            |= Parser.oneOf
                [ 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))

Added stdlib/lib/useless/junk version [a7ffc6f8bf].

Added stdlib/lib/version/play.json version [73b800a441].

























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
{
    "name": "play/version",
    "version": "1.0.0",
    "language-version": "0.2.0",
    "exposed-modules": [
        "version/data"
    ],
    "dependencies": {
    },
    "package-paths": [
    ]
}

Added stdlib/lib/version/src/version/data.play version [f4d9804625].





>
>
1
2
def: minor
: 1

Added stdlib/play.json version [163a77ae7d].





























>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
    "name": "play/standard_library",
    "version": "0.2.0",
    "language-version": "0.2.0",
    "exposed-modules": [
        "basic"
    ],
    "dependencies": {
        "play/version": "1.0.0"
    },
    "package-paths": [
        "lib/*"
    ]
}

Added stdlib/src/basic.play version [0ef79cb1cb].





>
>
1
2
def: version
: tmp/mod/major /version/data/minor + 

Added stdlib/src/tmp/mod.play version [2e69dc67e4].





>
>
1
2
def: major
: 2

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

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
..
61
62
63
64
65
66
67

68

69
70
71
72
73
74
75
..
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
...
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
...
215
216
217
218
219
220
221

222
223
224
225
226
227
228
229
...
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import Play.Qualifier as Qualifier
import Test exposing (Test, describe, test)
import Test.Qualifier.Util as Util


suite : Test
suite =







    describe "PackageLoader"
        [ test "Passes the load package metadata step" <|
            \_ ->
                PackageLoader.init "/project"
                    |> Expect.equal (PackageLoader.Initializing <| PackageLoader.ReadFile "/project" "play.json")
        , test "Retrieves necessary files" <|
            \_ ->
                PackageLoader.init "/project"
                    |> expectSideEffects testFiles
                        [ PackageLoader.ReadFile "/project" "play.json"
                        , PackageLoader.ResolveDirectories "/project/lib"
                        , PackageLoader.ReadFile "/project/lib/template_strings" "play.json"

                        , PackageLoader.ReadFile "/project/lib/template_strings/lib/version" "play.json"
                        , PackageLoader.ReadFile "/project/lib/unused" "play.json"
                        , 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 "/project"




                            |> resolveSideEffects testFiles []
                            |> Result.map Tuple.second
                in
                case loaderResult of
                    Err msg ->
                        Expect.fail msg

................................................................................
                                            Qualifier.SoloImpl
                                                [ Qualifier.Word emptyRange "/play/version/version/data/number"
                                                , Qualifier.Integer emptyRange 1
                                                , Qualifier.Builtin emptyRange Builtin.Plus
                                                ]
                                      }
                                    , { name = "/play/version/version/data/number"

                                      , metadata = Metadata.default

                                      , implementation =
                                            Qualifier.SoloImpl
                                                [ Qualifier.Integer emptyRange 2
                                                ]
                                      }
                                    ]
                            }
................................................................................
        Err msg ->
            Expect.fail msg

        Ok ( seenSfs, _ ) ->
            let
                sfDiff =
                    List.filter (\sf -> not <| List.member sf expectedSFs) seenSfs



            in
            Expect.equalLists [] sfDiff


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

                _ ->
                    Err <| "Expected model be Done, was: " ++ Debug.toString model
................................................................................
        case pathParts of
            [ _, "play.json" ] ->
                True

            _ ->
                False


getSideEffect : PackageLoader.Model -> Maybe PackageLoader.SideEffect
getSideEffect model =
    case model of
        PackageLoader.Done _ ->
            Nothing

        PackageLoader.Failed _ ->
            Nothing

        PackageLoader.Initializing sf ->
            Just sf

        PackageLoader.LoadingMetadata _ _ sf ->
            Just sf

        PackageLoader.ResolvingModulePaths _ _ sf ->
            Just sf

        PackageLoader.Compiling _ _ sf ->
            Just sf


testFiles : Dict String String
testFiles =
    Dict.fromList
        [ ( "/project/play.json"
          , """
            {
................................................................................
                    "mod1"
                ],
                "dependencies": {
                    "jarvis/template_strings": "1.2.0",
                    "play/version": "1.0.0"
                },
                "package-paths": [

                    "lib/*"
                ]
            }
            """
          )
        , ( "/project/src/mod1.play"
          , """
            def: next-version
................................................................................
                "exposed-modules": [
                    "template_strings/mod"
                ],
                "dependencies": {
                    "play/version": "1.1.0"
                },
                "package-paths": [
                    "lib/version"
                ]
            }
          """
          )
        , ( "/project/lib/template_strings/src/template_strings/mod.play"
          , """
            def: dec







>
>
>
>
>
>
>



|
|


|


<

>













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







 







>
|
>







 







>
>
>

|








|







 







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







 







>
|







 







|







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
...
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
...
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
...
228
229
230
231
232
233
234






















235
236
237
238
239
240
241
...
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
...
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import Play.Qualifier as Qualifier
import Test exposing (Test, describe, test)
import Test.Qualifier.Util as Util


suite : Test
suite =
    let
        initOpts =
            { projectDirPath = "/project"
            , possibleEntryPoint = Nothing
            , stdLibPath = "/project/lib/unused"
            }
    in
    describe "PackageLoader"
        [ test "Passes the load package metadata step" <|
            \_ ->
                PackageLoader.init initOpts
                    |> Expect.equal (PackageLoader.Initializing initOpts <| PackageLoader.ReadFile "/project" "play.json")
        , test "Retrieves necessary files" <|
            \_ ->
                PackageLoader.init initOpts
                    |> expectSideEffects testFiles
                        [ PackageLoader.ReadFile "/project" "play.json"

                        , PackageLoader.ReadFile "/project/lib/template_strings" "play.json"
                        , PackageLoader.ResolveDirectories "/project/lib/template_strings/lib"
                        , PackageLoader.ReadFile "/project/lib/template_strings/lib/version" "play.json"
                        , PackageLoader.ReadFile "/project/lib/unused" "play.json"
                        , 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
                case loaderResult of
                    Err msg ->
                        Expect.fail msg

                    Ok ast ->
                        Expect.equal
                            { types =
                                Dict.fromListBy Qualifier.typeDefinitionName []
                            , words =
                                Dict.fromListBy .name
                                    [ { name = "/robheghan/fnv/mod1/next-version"
                                      , metadata = Metadata.default
                                      , implementation =
                                            Qualifier.SoloImpl
                                                [ Qualifier.Word emptyRange "/play/version/version/data/number"
                                                , Qualifier.Integer emptyRange 1
                                                , Qualifier.Builtin emptyRange Builtin.Plus
                                                ]
                                      }
                                    , { name = "/play/version/version/data/number"
                                      , 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
                            { projectDirPath = "/project"
                            , possibleEntryPoint = Just "/play/version/version/data/number"
                            , stdLibPath = initOpts.stdLibPath
                            }
                            |> resolveSideEffects testFiles []
                            |> Result.map Tuple.second
                in
                case loaderResult of
                    Err msg ->
                        Expect.fail msg

................................................................................
                                            Qualifier.SoloImpl
                                                [ Qualifier.Word emptyRange "/play/version/version/data/number"
                                                , Qualifier.Integer emptyRange 1
                                                , Qualifier.Builtin emptyRange Builtin.Plus
                                                ]
                                      }
                                    , { name = "/play/version/version/data/number"
                                      , metadata =
                                            Metadata.default
                                                |> Metadata.asEntryPoint
                                      , implementation =
                                            Qualifier.SoloImpl
                                                [ Qualifier.Integer emptyRange 2
                                                ]
                                      }
                                    ]
                            }
................................................................................
        Err msg ->
            Expect.fail msg

        Ok ( seenSfs, _ ) ->
            let
                sfDiff =
                    List.filter (\sf -> not <| List.member sf expectedSFs) seenSfs

                sfDiffRev =
                    List.filter (\sf -> not <| List.member sf seenSfs) expectedSFs
            in
            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 )

                _ ->
                    Err <| "Expected model be Done, was: " ++ Debug.toString model
................................................................................
        case pathParts of
            [ _, "play.json" ] ->
                True

            _ ->
                False
























testFiles : Dict String String
testFiles =
    Dict.fromList
        [ ( "/project/play.json"
          , """
            {
................................................................................
                    "mod1"
                ],
                "dependencies": {
                    "jarvis/template_strings": "1.2.0",
                    "play/version": "1.0.0"
                },
                "package-paths": [
                    "lib/template_strings",
                    "lib/version"
                ]
            }
            """
          )
        , ( "/project/src/mod1.play"
          , """
            def: next-version
................................................................................
                "exposed-modules": [
                    "template_strings/mod"
                ],
                "dependencies": {
                    "play/version": "1.1.0"
                },
                "package-paths": [
                    "lib/*"
                ]
            }
          """
          )
        , ( "/project/lib/template_strings/src/template_strings/mod.play"
          , """
            def: dec

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

764
765
766
767
768
769
770






























771
772
773
774
775
776
777
                                      , 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







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







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
                                      , 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