Stabel

Check-in [7aabb3c813]
Login
Overview
Comment:Add array literals and a few builtins. [ccf0c23cc5] [839b5c7d9a]
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: 7aabb3c81384f81672185589990e732a3477bfa0419bc036e6694f353341bac4
User & Date: robin.hansen on 2021-09-01 04:29:06
Other Links: manifest | tags
Context
2021-09-01
05:19
Fix issues found with elm-review. check-in: f7ed530f30 user: robin.hansen tags: trunk
04:29
Add array literals and a few builtins. [ccf0c23cc5] [839b5c7d9a] check-in: 7aabb3c813 user: robin.hansen tags: trunk
04:26
Solve remaining issue by sorting the list of types before creating a boxMap. Closed-Leaf check-in: 1a424e8e29 user: robin.hansen tags: arrays
2021-08-18
06:45
Bump dependencies and update lock file with latest npm. Wasm tests now execute faster. check-in: a8431084c1 user: robin.hansen tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Modified src/Stabel/Codegen.elm from [7fa0842924] to [a26ff5ae8f].

70
71
72
73
74
75
76

77
78
79
80
81
82
83
...
182
183
184
185
186
187
188























189
190
191
192
193
194
195
...
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
...
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
...
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
...
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
...
694
695
696
697
698
699
700








































701
702
703
704
705
706
707
...
809
810
811
812
813
814
815















816
817
818
819
820
821


-- Codegen


type AstNode
    = IntLiteral Int

    | Function Int String -- id name
    | FunctionRef Int String -- id name
    | ConstructType Int Int -- id memberQty
    | SetMember Int Int -- offset memberQty
    | GetMember Int -- offset
    | Builtin Builtin
    | Box Int Int -- stackIdx typeId
................................................................................
    let
        ( newNode, updatedContext ) =
            case node of
                AST.IntLiteral _ val ->
                    ( IntLiteral val
                    , context
                    )
























                AST.Function _ fn _ ->
                    let
                        ( fnId, newContext ) =
                            idForFunction fn.name context
                    in
                    ( Function fnId fn.name
................................................................................

                AST.GetMember _ _ memberIndex _ ->
                    ( GetMember memberIndex
                    , context
                    )

        nodeType =
            case node of
                AST.IntLiteral _ _ ->
                    { input = []
                    , output = [ Type.Int ]
                    }

                AST.Function _ _ type_ ->
                    type_

                AST.FunctionRef _ fn ->
                    { input = []
                    , output = [ Type.FunctionSignature fn.type_ ]
                    }

                AST.Recurse _ ->
                    def.type_

                AST.Cycle _ data ->
                    data.typeSignature

                AST.Builtin _ builtin ->
                    Builtin.functionType builtin

                AST.ConstructType typeDef ->
                    case typeDef.members of
                        StructMembers members ->
                            { input = List.map Tuple.second members
                            , output = [ typeFromTypeDef typeDef.name typeDef.generics ]
                            }

                        UnionMembers members ->
                            -- Cannot happen
                            { input = members
                            , output = [ typeFromTypeDef typeDef.name typeDef.generics ]
                            }

                AST.SetMember typeDef _ _ memberType ->
                    let
                        type_ =
                            typeFromTypeDef typeDef.name typeDef.generics
                    in
                    { input = [ type_, memberType ]
                    , output = [ type_ ]
                    }

                AST.GetMember typeDef _ _ memberType ->
                    let
                        type_ =
                            typeFromTypeDef typeDef.name typeDef.generics
                    in
                    { input = [ type_ ]
                    , output = [ memberType ]
                    }

        typeFromTypeDef typeName gens =
            if List.isEmpty gens then
                Type.Custom typeName

            else
                Type.CustomGeneric typeName (List.map Type.Generic gens)

        stackInScope =
            List.reverse stack
                |> List.take (List.length nodeType.input)
                |> List.reverse

        stackElementsToBox =
................................................................................
                |> List.filterMap maybeBox
                |> maybeCons maybeBoxLeadingElement

        maybeBox ( idx, leftType, rightType ) =
            case ( leftType, rightType ) of
                ( _, Type.Union _ members ) ->
                    unionBoxMap members
                        |> List.find (\( t, _ ) -> t == leftType)
                        |> Maybe.map Tuple.second
                        |> Maybe.map (Box idx)

                _ ->
                    Nothing

        maybeBoxLeadingElement =
            case ( List.head stackInScope, isMultiFunction node, List.head nodeType.input ) of
                ( Just _, True, Just (Type.Union _ _) ) ->
                    -- Already handled by maybePromoteInt
                    Nothing

                ( Just _, True, Just nodeLeadingType ) ->
                    if requiresBoxingInPatternMatch nodeLeadingType then
                        let
                            idx =
                                max 0 (List.length nodeType.input - 1)
................................................................................
                |> List.reverse
    in
    ( newStack
    , newNode :: (stackElementsToBox ++ result)
    , updatedContext
    )









































































memberSize : AST.TypeDefinition -> Int
memberSize def =
    case def.members of
        StructMembers members ->
            List.length members

        UnionMembers members ->
            List.length members


unionBoxMap : List Type -> List ( Type, Int )
unionBoxMap union =
    let
        helper t ( nextId, mapping ) =
            if requiresBoxingInPatternMatch t then
                ( nextId - 1
                , ( t, nextId ) :: mapping
                )

            else
                ( nextId, mapping )
    in


    List.foldl helper ( -1, [] ) union
        |> Tuple.second


requiresBoxingInPatternMatch : Type -> Bool
requiresBoxingInPatternMatch type_ =
    case type_ of
        Type.Int ->
            True

        Type.Generic _ ->
            True




        _ ->
            False


multiFnToInstructions :
    Context
................................................................................
    -> Int
    -> Context
    -> ( Wasm.Instruction, Context )
makeInequalityTest boxMap selfIndex ((AST.TypeMatch _ typeFromTypeMatch _) as t_) localIdx context =
    let
        maybeBoxId =
            boxMap
                |> List.find (\( boxedType, _ ) -> boxedType == typeFromTypeMatch)
                |> Maybe.map Tuple.second
    in
    case ( t_, maybeBoxId ) of
        ( AST.TypeMatch _ Type.Int conditions, Just boxId ) ->
            ( Wasm.Batch
                [ Wasm.Local_Get localIdx
                , Wasm.I32_Load -- Load instance id
................................................................................
    case node of
        IntLiteral value ->
            Wasm.Batch
                [ Wasm.I32_Const value
                , BaseModule.callStackPushFn
                ]









































        Function id name ->
            Wasm.Call id name

        FunctionRef _ name ->
            let
                indexOfId =
                    indexOf name context.inlineFunctionNames
................................................................................

                Builtin.StackLeftRotate ->
                    BaseModule.callLeftRotFn

                Builtin.Apply ->
                    BaseModule.callExecInlineFn
















        Box stackPos id ->
            Wasm.Batch
                [ Wasm.I32_Const stackPos
                , Wasm.I32_Const id
                , BaseModule.callBoxFn
                ]







>







 







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







 







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







 







|









|







 







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












|










>
>
|











>
>
>







 







|







 







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







 







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






70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
...
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
...
268
269
270
271
272
273
274
275



























































276
277
278
279
280
281
282
...
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
...
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
...
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
...
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
...
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


-- Codegen


type AstNode
    = IntLiteral Int
    | ArrayLiteral Type (List ( Type, AstNode ))
    | Function Int String -- id name
    | FunctionRef Int String -- id name
    | ConstructType Int Int -- id memberQty
    | SetMember Int Int -- offset memberQty
    | GetMember Int -- offset
    | Builtin Builtin
    | Box Int Int -- stackIdx typeId
................................................................................
    let
        ( newNode, updatedContext ) =
            case node of
                AST.IntLiteral _ val ->
                    ( IntLiteral val
                    , context
                    )

                AST.ArrayLiteral _ nodes arrayType ->
                    let
                        ( _, codeGenNodesReversed, nextContext ) =
                            List.foldl
                                (astNodeToCodegenNode def)
                                ( [], [], context )
                                nodes

                        codeGenNodes =
                            List.reverse codeGenNodesReversed

                        codeGenTypes =
                            nodes
                                |> List.map (typeOfNode def)
                                |> List.map (\ft -> Maybe.withDefault Type.Int <| List.head ft.output)

                        codeGenTuples =
                            List.map2 Tuple.pair codeGenTypes codeGenNodes
                    in
                    ( ArrayLiteral arrayType codeGenTuples
                    , nextContext
                    )

                AST.Function _ fn _ ->
                    let
                        ( fnId, newContext ) =
                            idForFunction fn.name context
                    in
                    ( Function fnId fn.name
................................................................................

                AST.GetMember _ _ memberIndex _ ->
                    ( GetMember memberIndex
                    , context
                    )

        nodeType =
            typeOfNode def node




























































        stackInScope =
            List.reverse stack
                |> List.take (List.length nodeType.input)
                |> List.reverse

        stackElementsToBox =
................................................................................
                |> List.filterMap maybeBox
                |> maybeCons maybeBoxLeadingElement

        maybeBox ( idx, leftType, rightType ) =
            case ( leftType, rightType ) of
                ( _, Type.Union _ members ) ->
                    unionBoxMap members
                        |> List.find (\( t, _ ) -> Type.equalBaseType t leftType)
                        |> Maybe.map Tuple.second
                        |> Maybe.map (Box idx)

                _ ->
                    Nothing

        maybeBoxLeadingElement =
            case ( List.head stackInScope, isMultiFunction node, List.head nodeType.input ) of
                ( Just _, True, Just (Type.Union _ _) ) ->
                    -- Already handled by maybeBox
                    Nothing

                ( Just _, True, Just nodeLeadingType ) ->
                    if requiresBoxingInPatternMatch nodeLeadingType then
                        let
                            idx =
                                max 0 (List.length nodeType.input - 1)
................................................................................
                |> List.reverse
    in
    ( newStack
    , newNode :: (stackElementsToBox ++ result)
    , updatedContext
    )


typeOfNode : AST.FunctionDefinition -> AST.AstNode -> Type.FunctionType
typeOfNode def node =
    case node of
        AST.IntLiteral _ _ ->
            { input = []
            , output = [ Type.Int ]
            }

        AST.ArrayLiteral _ _ t ->
            { input = []
            , output = [ t ]
            }

        AST.Function _ _ type_ ->
            type_

        AST.FunctionRef _ fn ->
            { input = []
            , output = [ Type.FunctionSignature fn.type_ ]
            }

        AST.Recurse _ ->
            def.type_

        AST.Cycle _ data ->
            data.typeSignature

        AST.Builtin _ builtin ->
            Builtin.functionType builtin

        AST.ConstructType typeDef ->
            case typeDef.members of
                StructMembers members ->
                    { input = List.map Tuple.second members
                    , output = [ typeFromTypeDef typeDef.name typeDef.generics ]
                    }

                UnionMembers members ->
                    -- Cannot happen
                    { input = members
                    , output = [ typeFromTypeDef typeDef.name typeDef.generics ]
                    }

        AST.SetMember typeDef _ _ memberType ->
            let
                type_ =
                    typeFromTypeDef typeDef.name typeDef.generics
            in
            { input = [ type_, memberType ]
            , output = [ type_ ]
            }

        AST.GetMember typeDef _ _ memberType ->
            let
                type_ =
                    typeFromTypeDef typeDef.name typeDef.generics
            in
            { input = [ type_ ]
            , output = [ memberType ]
            }


typeFromTypeDef : String -> List String -> Type
typeFromTypeDef typeName gens =
    if List.isEmpty gens then
        Type.Custom typeName

    else
        Type.CustomGeneric typeName (List.map Type.Generic gens)


memberSize : AST.TypeDefinition -> Int
memberSize def =
    case def.members of
        StructMembers members ->
            List.length members

        UnionMembers members ->
            List.length members


unionBoxMap : List Type -> List ( Type, Int )
unionBoxMap unionMembers =
    let
        helper t ( nextId, mapping ) =
            if requiresBoxingInPatternMatch t then
                ( nextId - 1
                , ( t, nextId ) :: mapping
                )

            else
                ( nextId, mapping )
    in
    unionMembers
        |> List.sortWith Type.compareBaseType
        |> List.foldl helper ( -1, [] )
        |> Tuple.second


requiresBoxingInPatternMatch : Type -> Bool
requiresBoxingInPatternMatch type_ =
    case type_ of
        Type.Int ->
            True

        Type.Generic _ ->
            True

        Type.Array _ ->
            True

        _ ->
            False


multiFnToInstructions :
    Context
................................................................................
    -> Int
    -> Context
    -> ( Wasm.Instruction, Context )
makeInequalityTest boxMap selfIndex ((AST.TypeMatch _ typeFromTypeMatch _) as t_) localIdx context =
    let
        maybeBoxId =
            boxMap
                |> List.find (\( boxedType, _ ) -> Type.equalBaseType boxedType typeFromTypeMatch)
                |> Maybe.map Tuple.second
    in
    case ( t_, maybeBoxId ) of
        ( AST.TypeMatch _ Type.Int conditions, Just boxId ) ->
            ( Wasm.Batch
                [ Wasm.Local_Get localIdx
                , Wasm.I32_Load -- Load instance id
................................................................................
    case node of
        IntLiteral value ->
            Wasm.Batch
                [ Wasm.I32_Const value
                , BaseModule.callStackPushFn
                ]

        ArrayLiteral arrayType typedNodes ->
            case arrayType of
                Type.Array (Type.Union _ unionMembers) ->
                    let
                        boxMap =
                            unionBoxMap unionMembers

                        boxedNodes =
                            List.map
                                (\( nType, n ) ->
                                    ( List.find (\( t, _ ) -> Type.equalBaseType t nType) boxMap
                                        |> Maybe.map Tuple.second
                                        |> Maybe.withDefault -1
                                    , n
                                    )
                                )
                                typedNodes
                    in
                    Wasm.Batch <|
                        BaseModule.callArrayEmptyFn
                            :: List.concatMap
                                (\( tag, n ) ->
                                    [ nodeToInstruction context n
                                    , nodeToInstruction context <| Box 0 tag
                                    , BaseModule.callArrayPushFn
                                    ]
                                )
                                boxedNodes

                _ ->
                    Wasm.Batch <|
                        BaseModule.callArrayEmptyFn
                            :: List.concatMap
                                (\( _, n ) ->
                                    [ nodeToInstruction context n
                                    , BaseModule.callArrayPushFn
                                    ]
                                )
                                typedNodes

        Function id name ->
            Wasm.Call id name

        FunctionRef _ name ->
            let
                indexOfId =
                    indexOf name context.inlineFunctionNames
................................................................................

                Builtin.StackLeftRotate ->
                    BaseModule.callLeftRotFn

                Builtin.Apply ->
                    BaseModule.callExecInlineFn

                Builtin.ArrayEmpty ->
                    BaseModule.callArrayEmptyFn

                Builtin.ArrayLength ->
                    BaseModule.callArrayLengthFn

                Builtin.ArrayPush ->
                    BaseModule.callArrayPushFn

                Builtin.ArrayGet ->
                    BaseModule.callArrayGetFn

                Builtin.ArraySet ->
                    BaseModule.callArraySetFn

        Box stackPos id ->
            Wasm.Batch
                [ Wasm.I32_Const stackPos
                , Wasm.I32_Const id
                , BaseModule.callBoxFn
                ]

Modified src/Stabel/Codegen/BaseModule.elm from [491f472a19] to [2e8537261e].

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
...
227
228
229
230
231
232
233


















































234
235
236
237
238
239
240
...
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
...
574
575
576
577
578
579
580
581





























































































































































































initialHeapPositionOffset : Int
initialHeapPositionOffset =
    stackPositionOffset + wasmPtrSize


firstAvailableFunctionId : Int
firstAvailableFunctionId =
    20



-- Bultin function names


allocFn : String
................................................................................


callExecInlineFn : Wasm.Instruction
callExecInlineFn =
    Wasm.Call 19 execInlineFn





















































-- Base module


baseModule : Wasm.Module
baseModule =
    let
................................................................................
      , name = copyStructFn
      , args = [ Wasm.Int32, Wasm.Int32 ]
      , results = [ Wasm.Int32 ]
      , locals = [ Wasm.Int32, Wasm.Int32 ]
      , instructions =
            [ Wasm.Local_Get 1 -- Size in bytes
            , callAllocFn
            , Wasm.Local_Set 2 -- Save output instance
            , Wasm.Block
                [ Wasm.Loop
                    [ Wasm.Local_Get 1
                    , Wasm.I32_EqZero
                    , Wasm.BreakIf 1 -- break out of loop
                    , Wasm.Local_Get 1
                    , Wasm.I32_Const wasmPtrSize
                    , Wasm.I32_Sub
                    , Wasm.Local_Set 1 -- Decreased pointer size
                    , Wasm.Local_Get 0 -- Source struct
                    , Wasm.Local_Get 1
                    , Wasm.I32_Add
                    , Wasm.I32_Load -- Get a byte from source struct
                    , Wasm.Local_Set 3 -- Save byte to copy
                    , Wasm.Local_Get 2 -- Dest struct
                    , Wasm.Local_Get 1
                    , Wasm.I32_Add
                    , Wasm.Local_Get 3
                    , Wasm.I32_Store -- Copy byte from source to dest struct
                    , Wasm.Break 0 -- loop
                    ]
                ]
            , Wasm.Local_Get 2
            ]
      }
    , { id = 3
      , name = stackPushFn
      , args = [ Wasm.Int32 ]
      , results = []
................................................................................
      , results = []
      , locals = []
      , instructions =
            [ callStackPopFn
            , Wasm.CallIndirect
            ]
      }
    ]




































































































































































































|







 







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







 







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







 







|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
...
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
...
335
336
337
338
339
340
341






342




343




344
345





346
347
348
349
350
351
352
...
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
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
initialHeapPositionOffset : Int
initialHeapPositionOffset =
    stackPositionOffset + wasmPtrSize


firstAvailableFunctionId : Int
firstAvailableFunctionId =
    List.length baseFunctions



-- Bultin function names


allocFn : String
................................................................................


callExecInlineFn : Wasm.Instruction
callExecInlineFn =
    Wasm.Call 19 execInlineFn


arrayEmptyFn : String
arrayEmptyFn =
    "__array_empty"


callArrayEmptyFn : Wasm.Instruction
callArrayEmptyFn =
    Wasm.Call 20 arrayEmptyFn


arrayLengthFn : String
arrayLengthFn =
    "__array_length"


callArrayLengthFn : Wasm.Instruction
callArrayLengthFn =
    Wasm.Call 21 arrayLengthFn


arrayPushFn : String
arrayPushFn =
    "__array_push"


callArrayPushFn : Wasm.Instruction
callArrayPushFn =
    Wasm.Call 22 arrayPushFn


arrayGetFn : String
arrayGetFn =
    "__array_get"


callArrayGetFn : Wasm.Instruction
callArrayGetFn =
    Wasm.Call 23 arrayGetFn


arraySetFn : String
arraySetFn =
    "__array_set"


callArraySetFn : Wasm.Instruction
callArraySetFn =
    Wasm.Call 24 arraySetFn



-- Base module


baseModule : Wasm.Module
baseModule =
    let
................................................................................
      , name = copyStructFn
      , args = [ Wasm.Int32, Wasm.Int32 ]
      , results = [ Wasm.Int32 ]
      , locals = [ Wasm.Int32, Wasm.Int32 ]
      , instructions =
            [ Wasm.Local_Get 1 -- Size in bytes
            , callAllocFn






            , Wasm.Local_Tee 2 -- Output struct




            , Wasm.Local_Get 0 -- Original struct




            , Wasm.Local_Get 1
            , Wasm.Memory_Copy





            , Wasm.Local_Get 2
            ]
      }
    , { id = 3
      , name = stackPushFn
      , args = [ Wasm.Int32 ]
      , results = []
................................................................................
      , results = []
      , locals = []
      , instructions =
            [ callStackPopFn
            , Wasm.CallIndirect
            ]
      }

    -- ARRAY
    , { id = 20
      , name = arrayEmptyFn
      , args = []
      , results = []
      , locals = [ Wasm.Int32 ]
      , instructions =
            [ Wasm.I32_Const 4 -- Just enough space for length variable
            , callAllocFn
            , Wasm.Local_Tee 0 -- Save output instance
            , Wasm.I32_Const 0
            , Wasm.I32_Store -- Set length to 0
            , Wasm.Local_Get 0
            , callStackPushFn
            ]
      }
    , { id = 21
      , name = arrayLengthFn
      , args = []
      , results = []
      , locals = []
      , instructions =
            [ callStackPopFn
            , Wasm.I32_Load
            , callStackPushFn
            ]
      }
    , { id = 22
      , name = arrayPushFn
      , args = []
      , results = []
      , locals = [ Wasm.Int32, Wasm.Int32, Wasm.Int32, Wasm.Int32 ]
      , instructions =
            [ callStackPopFn
            , Wasm.Local_Set 3 -- object to push
            , callStackPopFn
            , Wasm.Local_Tee 0 -- original array pointer
            , Wasm.I32_Load
            , Wasm.Local_Tee 1 -- original array length
            , Wasm.I32_Const wasmPtrSize
            , Wasm.I32_Mul -- bytes required for new array
            , Wasm.I32_Const (wasmPtrSize * 2)
            , Wasm.I32_Add -- plus length and new object
            , callAllocFn
            , Wasm.Local_Tee 2 -- new array pointer

            -- Set length
            , Wasm.Local_Get 1
            , Wasm.I32_Const 1
            , Wasm.I32_Add
            , Wasm.I32_Store -- store length in new array

            -- Copy
            , Wasm.Local_Get 2
            , Wasm.I32_Const wasmPtrSize
            , Wasm.I32_Add -- new array content start ptr
            , Wasm.Local_Get 0
            , Wasm.I32_Const wasmPtrSize
            , Wasm.I32_Add -- original array content start ptr
            , Wasm.Local_Get 1
            , Wasm.I32_Const wasmPtrSize
            , Wasm.I32_Mul -- bytes to copy to new array
            , Wasm.Memory_Copy

            -- Set new object
            , Wasm.Local_Get 2
            , Wasm.Local_Get 2
            , Wasm.I32_Load
            , Wasm.I32_Const wasmPtrSize
            , Wasm.I32_Mul
            , Wasm.I32_Add -- Last object pos
            , Wasm.Local_Get 3
            , Wasm.I32_Store

            -- Return
            , Wasm.Local_Get 2
            , callStackPushFn
            ]
      }
    , { id = 23
      , name = arrayGetFn
      , args = []
      , results = []
      , locals = [ Wasm.Int32, Wasm.Int32 ]
      , instructions =
            [ callStackPopFn
            , Wasm.Local_Set 0 -- index to get
            , callStackPopFn
            , Wasm.Local_Set 1 -- array
            , Wasm.Block
                [ -- check for negative index
                  Wasm.Local_Get 0
                , Wasm.I32_Const 0
                , Wasm.I32_LT
                , Wasm.BreakIf 0

                -- Check for index too large
                , Wasm.Local_Get 0
                , Wasm.Local_Get 1
                , Wasm.I32_Load -- length of array
                , Wasm.I32_GTE
                , Wasm.BreakIf 0

                -- Get element at index
                , Wasm.Local_Get 1
                , Wasm.I32_Const wasmPtrSize
                , Wasm.I32_Add -- move pointer beyond length
                , Wasm.Local_Get 0
                , Wasm.I32_Const wasmPtrSize
                , Wasm.I32_Mul -- offset
                , Wasm.I32_Add -- starting position + offset = ptr to element
                , Wasm.I32_Load -- element to return
                , Wasm.I32_Const 1 -- success flag
                , callStackPushFn
                , callStackPushFn
                , Wasm.Return
                ]

            -- Failure case
            , Wasm.I32_Const 0
            , Wasm.I32_Const 0
            , callStackPushFn
            , callStackPushFn
            ]
      }
    , { id = 24
      , name = arraySetFn
      , args = []
      , results = []
      , locals = [ Wasm.Int32, Wasm.Int32, Wasm.Int32, Wasm.Int32, Wasm.Int32 ]
      , instructions =
            [ callStackPopFn
            , Wasm.Local_Set 0 -- index
            , callStackPopFn
            , Wasm.Local_Set 1 -- new value
            , callStackPopFn
            , Wasm.Local_Set 2 -- original array
            , Wasm.Block
                [ -- Bounds check
                  -- Lower bound
                  Wasm.Local_Get 0
                , Wasm.I32_Const 0
                , Wasm.I32_LT
                , Wasm.BreakIf 0

                -- Upper bound
                , Wasm.Local_Get 0
                , Wasm.Local_Get 2
                , Wasm.I32_Load
                , Wasm.Local_Tee 3 -- original array length
                , Wasm.I32_GTE
                , Wasm.BreakIf 0

                -- Copy original array
                , Wasm.Local_Get 3
                , Wasm.I32_Const wasmPtrSize
                , Wasm.I32_Mul
                , Wasm.I32_Const wasmPtrSize
                , Wasm.I32_Add -- Size of original array in bytes
                , Wasm.Local_Tee 3 -- overwrite
                , callAllocFn
                , Wasm.Local_Tee 4 -- New array
                , Wasm.Local_Get 2
                , Wasm.Local_Get 3
                , Wasm.Memory_Copy

                -- Set element at idx
                , Wasm.Local_Get 0
                , Wasm.I32_Const 1
                , Wasm.I32_Add -- to 'jump over' the length field of the array
                , Wasm.I32_Const wasmPtrSize
                , Wasm.I32_Mul -- offset
                , Wasm.Local_Get 4
                , Wasm.I32_Add -- address of idx in new array
                , Wasm.Local_Get 1
                , Wasm.I32_Store

                --Return
                , Wasm.Local_Get 4
                , callStackPushFn
                , Wasm.Return
                ]

            -- Failure case
            , Wasm.Local_Get 2
            , callStackPushFn
            ]
      }
    ]

Modified src/Stabel/Data/Builtin.elm from [65af0595b2] to [bc2c41c8f3].

14
15
16
17
18
19
20





21
22
23
24
25
26
27
..
79
80
81
82
83
84
85

























    | Equal
    | StackDuplicate
    | StackDrop
    | StackSwap
    | StackRightRotate
    | StackLeftRotate
    | Apply







functionType : Builtin -> FunctionType
functionType builtin =
    case builtin of
        Plus ->
            { input = [ Type.Int, Type.Int ]
................................................................................
                , Type.FunctionSignature
                    { input = [ Type.StackRange "a" ]
                    , output = [ Type.StackRange "b" ]
                    }
                ]
            , output = [ Type.StackRange "b" ]
            }
































>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
14
15
16
17
18
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    | Equal
    | StackDuplicate
    | StackDrop
    | StackSwap
    | StackRightRotate
    | StackLeftRotate
    | Apply
    | ArrayEmpty
    | ArrayLength
    | ArrayPush
    | ArrayGet
    | ArraySet


functionType : Builtin -> FunctionType
functionType builtin =
    case builtin of
        Plus ->
            { input = [ Type.Int, Type.Int ]
................................................................................
                , Type.FunctionSignature
                    { input = [ Type.StackRange "a" ]
                    , output = [ Type.StackRange "b" ]
                    }
                ]
            , output = [ Type.StackRange "b" ]
            }

        ArrayEmpty ->
            { input = []
            , output = [ Type.Array (Type.Generic "a") ]
            }

        ArrayLength ->
            { input = [ Type.Array (Type.Generic "a") ]
            , output = [ Type.Int ]
            }

        ArrayPush ->
            { input = [ Type.Array (Type.Generic "a"), Type.Generic "a" ]
            , output = [ Type.Array (Type.Generic "a") ]
            }

        ArrayGet ->
            { input = [ Type.Array (Type.Generic "a"), Type.Int ]
            , output = [ Type.Int, Type.Generic "a" ]
            }

        ArraySet ->
            { input = [ Type.Array (Type.Generic "a"), Type.Generic "a", Type.Int ]
            , output = [ Type.Array (Type.Generic "a") ]
            }

Modified src/Stabel/Data/Type.elm from [69ab1cb9cc] to [c48106c77e].

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
..
70
71
72
73
74
75
76



77
78
79
80
81
82
83
..
92
93
94
95
96
97
98



99
100
101















































102
103
104
105
106
107
108
...
136
137
138
139
140
141
142



143
144
145
146
147
148
149
...
176
177
178
179
180
181
182



183
184
185
186
187
188
189
...
303
304
305
306
307
308
309











310
311
312
313
314
315
316
module Stabel.Data.Type exposing
    ( FunctionType
    , Type(..)

    , compatibleFunctions
    , emptyFunctionType

    , functionTypeToString
    , genericName
    , genericlyCompatible
    , isGeneric
    , referencedGenerics
    , toDisplayString
    )

import Dict exposing (Dict)
import Set exposing (Set)






type Type
    = Int
    | Generic String
    | Custom String
    | CustomGeneric String (List Type)
    | Union (Maybe String) (List Type)
    | FunctionSignature FunctionType
    | StackRange String



type alias FunctionType =
    { input : List Type
    , output : List Type
    }

................................................................................
                |> List.foldl Set.union Set.empty

        Union _ members ->
            members
                |> List.map referencedGenerics
                |> List.foldl Set.union Set.empty




        _ ->
            Set.empty


genericlyCompatible : Type -> Type -> Bool
genericlyCompatible lhs rhs =
    case ( lhs, rhs ) of
................................................................................

        ( CustomGeneric lName _, CustomGeneric rName _ ) ->
            lName == rName

        ( Union _ lMems, Union _ rMems ) ->
            lMems == rMems




        _ ->
            lhs == rhs

















































sameCategory : Type -> Type -> Bool
sameCategory lhs rhs =
    case ( lhs, rhs ) of
        ( FunctionSignature _, FunctionSignature _ ) ->
            True

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

        FunctionSignature _ ->
            "Function"

        StackRange name ->
            name ++ "..."





toDisplayString : Type -> String
toDisplayString t =
    case t of
        Int ->
            "Int"

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

        FunctionSignature quotType ->
            "[ " ++ functionTypeToString quotType ++ " ]"

        StackRange name ->
            name ++ "..."





functionTypeToString : FunctionType -> String
functionTypeToString functionType =
    let
        inputTypeStrings =
            List.map toDisplayString functionType.input

................................................................................
            let
                ( _, compatibleMembers ) =
                    compatibleTypeLists lMembers rMembers Dict.empty
            in
            if lName == rName && compatibleMembers then
                compatibleTypeLists annotatedRest inferredRest rangeDict












            else
                ( rangeDict, False )

        ( (Union _ lMembers) :: annotatedRest, (Union _ rMembers) :: inferredRest ) ->
            let
                lSet =
                    Set.fromList (List.map toString lMembers)



>


>











>
>
>
>









>







 







>
>
>







 







>
>
>



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







 







>
>
>







 







>
>
>







 







>
>
>
>
>
>
>
>
>
>
>







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
..
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
...
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
...
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
...
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
...
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
module Stabel.Data.Type exposing
    ( FunctionType
    , Type(..)
    , compareBaseType
    , compatibleFunctions
    , emptyFunctionType
    , equalBaseType
    , functionTypeToString
    , genericName
    , genericlyCompatible
    , isGeneric
    , referencedGenerics
    , toDisplayString
    )

import Dict exposing (Dict)
import Set exposing (Set)



-- TODO: Are all these functions still needed?


type Type
    = Int
    | Generic String
    | Custom String
    | CustomGeneric String (List Type)
    | Union (Maybe String) (List Type)
    | FunctionSignature FunctionType
    | StackRange String
    | Array Type


type alias FunctionType =
    { input : List Type
    , output : List Type
    }

................................................................................
                |> List.foldl Set.union Set.empty

        Union _ members ->
            members
                |> List.map referencedGenerics
                |> List.foldl Set.union Set.empty

        Array val ->
            referencedGenerics val

        _ ->
            Set.empty


genericlyCompatible : Type -> Type -> Bool
genericlyCompatible lhs rhs =
    case ( lhs, rhs ) of
................................................................................

        ( CustomGeneric lName _, CustomGeneric rName _ ) ->
            lName == rName

        ( Union _ lMems, Union _ rMems ) ->
            lMems == rMems

        ( Array lT, Array rT ) ->
            genericlyCompatible lT rT

        _ ->
            lhs == rhs


equalBaseType : Type -> Type -> Bool
equalBaseType lhs rhs =
    case ( lhs, rhs ) of
        ( Generic _, Generic _ ) ->
            True

        ( Array _, Array _ ) ->
            True

        ( CustomGeneric lName _, CustomGeneric rName _ ) ->
            lName == rName

        _ ->
            lhs == rhs


compareBaseType : Type -> Type -> Order
compareBaseType lhs rhs =
    compare
        (baseTypeToComparable lhs)
        (baseTypeToComparable rhs)


baseTypeToComparable : Type -> String
baseTypeToComparable t =
    case t of
        Int ->
            "int"

        Array _ ->
            "array"

        Generic val ->
            "gen_" ++ val

        Custom name ->
            "custom_" ++ name

        CustomGeneric name _ ->
            "custom_" ++ name

        _ ->
            -- the remaining types cannot be used ina  union,
            -- so the need for them to be sorted is 0
            ""


sameCategory : Type -> Type -> Bool
sameCategory lhs rhs =
    case ( lhs, rhs ) of
        ( FunctionSignature _, FunctionSignature _ ) ->
            True

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

        FunctionSignature _ ->
            "Function"

        StackRange name ->
            name ++ "..."

        Array _ ->
            "Array"


toDisplayString : Type -> String
toDisplayString t =
    case t of
        Int ->
            "Int"

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

        FunctionSignature quotType ->
            "[ " ++ functionTypeToString quotType ++ " ]"

        StackRange name ->
            name ++ "..."

        Array t_ ->
            "Array(" ++ toDisplayString t_ ++ ")"


functionTypeToString : FunctionType -> String
functionTypeToString functionType =
    let
        inputTypeStrings =
            List.map toDisplayString functionType.input

................................................................................
            let
                ( _, compatibleMembers ) =
                    compatibleTypeLists lMembers rMembers Dict.empty
            in
            if lName == rName && compatibleMembers then
                compatibleTypeLists annotatedRest inferredRest rangeDict

            else
                ( rangeDict, False )

        ( (Array lMember) :: annotatedRest, (Array rMember) :: inferredRest ) ->
            let
                ( _, compatibleMembers ) =
                    compatibleTypeLists [ lMember ] [ rMember ] Dict.empty
            in
            if compatibleMembers then
                compatibleTypeLists annotatedRest inferredRest rangeDict

            else
                ( rangeDict, False )

        ( (Union _ lMembers) :: annotatedRest, (Union _ rMembers) :: inferredRest ) ->
            let
                lSet =
                    Set.fromList (List.map toString lMembers)

Modified src/Stabel/Parser.elm from [3686af24e9] to [040268e985].

81
82
83
84
85
86
87

88
89
90
91
92
93
94
....
1044
1045
1046
1047
1048
1049
1050








1051
1052
1053
1054
1055
1056
1057
    | Function SourceLocationRange String
    | PackageFunction SourceLocationRange (List String) String
    | ExternalFunction SourceLocationRange (List String) String
    | InlineFunction SourceLocationRange (List AstNode)
    | ConstructType String
    | GetMember String String
    | SetMember String String



run : String -> String -> Result (List (Parser.DeadEnd Context Problem)) AST
run ref sourceCode =
    Parser.run (parser ref) sourceCode


................................................................................
        , Parser.succeed (\startLoc quotImpl endLoc -> Parser.Loop (InlineFunction (SourceLocationRange startLoc endLoc) quotImpl :: nodes))
            |= sourceLocationParser
            |. Parser.symbol (Token "[" ExpectedLeftBracket)
            |. noiseParser
            |= implementationParser
            |. Parser.symbol (Token "]" ExpectedRightBracket)
            |= sourceLocationParser








            |. noiseParser
        , Parser.succeed (Parser.Done (List.reverse nodes))
        ]


nodeParser : Parser AstNode
nodeParser =







>







 







>
>
>
>
>
>
>
>







81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
....
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
    | Function SourceLocationRange String
    | PackageFunction SourceLocationRange (List String) String
    | ExternalFunction SourceLocationRange (List String) String
    | InlineFunction SourceLocationRange (List AstNode)
    | ConstructType String
    | GetMember String String
    | SetMember String String
    | ArrayLiteral SourceLocationRange (List AstNode)


run : String -> String -> Result (List (Parser.DeadEnd Context Problem)) AST
run ref sourceCode =
    Parser.run (parser ref) sourceCode


................................................................................
        , Parser.succeed (\startLoc quotImpl endLoc -> Parser.Loop (InlineFunction (SourceLocationRange startLoc endLoc) quotImpl :: nodes))
            |= sourceLocationParser
            |. Parser.symbol (Token "[" ExpectedLeftBracket)
            |. noiseParser
            |= implementationParser
            |. Parser.symbol (Token "]" ExpectedRightBracket)
            |= sourceLocationParser
            |. noiseParser
        , Parser.succeed (\startLoc arrContent endLoc -> Parser.Loop (ArrayLiteral (SourceLocationRange startLoc endLoc) arrContent :: nodes))
            |= sourceLocationParser
            |. Parser.symbol (Token "{" ExpectedLeftCurly)
            |. noiseParser
            |= implementationParser
            |. Parser.symbol (Token "}" ExpectedRightCurly)
            |= sourceLocationParser
            |. noiseParser
        , Parser.succeed (Parser.Done (List.reverse nodes))
        ]


nodeParser : Parser AstNode
nodeParser =

Modified src/Stabel/Parser/Problem.elm from [de8ce45cbd] to [11e01b8df9].

40
41
42
43
44
45
46


47
48
49
50
51
52
53
...
216
217
218
219
220
221
222






223
224
225
226
227
228
229
    | UnexpectedMetadata
    | ExpectedLeftParen
    | ExpectedRightParen
    | ExpectedEndOfFile
    | ExpectedTypeSeperator
    | ExpectedLeftBracket
    | ExpectedRightBracket


    | FunctionAlreadyDefined String (Maybe SourceLocationRange)
    | TypeAlreadyDefined String SourceLocationRange
    | UnknownMetadata String
    | InvalidModulePath String
    | ModuleIsEmpty
    | BadDefinition String

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

        ExpectedLeftBracket ->
            "Expected opening bracket"

        ExpectedRightBracket ->
            "Expected closing bracket"







        FunctionAlreadyDefined functionName maybePreviousDefinitionRange ->
            case maybePreviousDefinitionRange of
                Nothing ->
                    "You're trying to define a new function called '"
                        ++ functionName
                        ++ "', but this function has already been defined."








>
>







 







>
>
>
>
>
>







40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
...
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
    | UnexpectedMetadata
    | ExpectedLeftParen
    | ExpectedRightParen
    | ExpectedEndOfFile
    | ExpectedTypeSeperator
    | ExpectedLeftBracket
    | ExpectedRightBracket
    | ExpectedLeftCurly
    | ExpectedRightCurly
    | FunctionAlreadyDefined String (Maybe SourceLocationRange)
    | TypeAlreadyDefined String SourceLocationRange
    | UnknownMetadata String
    | InvalidModulePath String
    | ModuleIsEmpty
    | BadDefinition String

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

        ExpectedLeftBracket ->
            "Expected opening bracket"

        ExpectedRightBracket ->
            "Expected closing bracket"

        ExpectedLeftCurly ->
            "Expected opening curly brace"

        ExpectedRightCurly ->
            "Expected closing curly brace"

        FunctionAlreadyDefined functionName maybePreviousDefinitionRange ->
            case maybePreviousDefinitionRange of
                Nothing ->
                    "You're trying to define a new function called '"
                        ++ functionName
                        ++ "', but this function has already been defined."

Modified src/Stabel/Qualifier.elm from [d0e65cfa74] to [39463bf45b].

93
94
95
96
97
98
99

100
101
102
103
104
105
106
...
115
116
117
118
119
120
121




122
123
124
125
126
127
128
...
452
453
454
455
456
457
458














459
460
461
462
463
464
465
...
884
885
886
887
888
889
890







891
892
893
894
895
896
897
....
1405
1406
1407
1408
1409
1410
1411






























1412
1413
1414
1415
1416
1417
1418
    | FunctionRef SourceLocationRange FunctionDefinition
    | Recurse SourceLocationRange
    | Cycle SourceLocationRange CycleData
    | Builtin SourceLocationRange Builtin
    | ConstructType TypeDefinition
    | GetMember TypeDefinition String Int Type
    | SetMember TypeDefinition String Int Type



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

................................................................................
        , ( "=", Builtin.Equal )
        , ( "swap", Builtin.StackSwap )
        , ( "dup", Builtin.StackDuplicate )
        , ( "drop", Builtin.StackDrop )
        , ( "rotate", Builtin.StackRightRotate )
        , ( "-rotate", Builtin.StackLeftRotate )
        , ( "!", Builtin.Apply )




        ]


type alias RunConfig =
    { packageName : String
    , modulePath : String
    , ast : Parser.AST
................................................................................
                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.TypeMatch range (Parser.LocalRef "Int" []) [ ( "value", Parser.LiteralInt val ) ] ->
            Ok <|
                TypeMatch
                    (qualifiedRange range)
                    Type.Int
                    [ TypeMatchCond "value" Type.Int (LiteralInt val) ]








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

        Parser.TypeMatch range (Parser.LocalRef name []) patterns ->
            case qualifiedNameToMatch (qualifiedRange range) (qualifyName config name) patterns of
                (Err (UnknownTypeRef _ _)) as errMsg ->
................................................................................
                            Ok (FunctionRef (mapLoc sourceLocation) qualifiedFunction)
                                :: acc.qualifiedNodes
                        , inlineFunctionNames =
                            acc.inlineFunctionNames
                                |> Set.union qualifyNodeResult.inlineFunctionNames
                                |> Set.insert inlineFuncName
                    }































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


isMultiFunction : Parser.FunctionDefinition -> Bool
isMultiFunction def =







>







 







>
>
>
>







 







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







 







>
>
>
>
>
>
>







 







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







93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
...
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
...
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
...
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
....
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
    | FunctionRef SourceLocationRange FunctionDefinition
    | Recurse SourceLocationRange
    | Cycle SourceLocationRange CycleData
    | Builtin SourceLocationRange Builtin
    | ConstructType TypeDefinition
    | GetMember TypeDefinition String Int Type
    | SetMember TypeDefinition String Int Type
    | ArrayLiteral SourceLocationRange (List Node)


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

................................................................................
        , ( "=", Builtin.Equal )
        , ( "swap", Builtin.StackSwap )
        , ( "dup", Builtin.StackDuplicate )
        , ( "drop", Builtin.StackDrop )
        , ( "rotate", Builtin.StackRightRotate )
        , ( "-rotate", Builtin.StackLeftRotate )
        , ( "!", Builtin.Apply )
        , ( "array-length", Builtin.ArrayLength )
        , ( "array-push", Builtin.ArrayPush )
        , ( "array-get", Builtin.ArrayGet )
        , ( "array-set", Builtin.ArraySet )
        ]


type alias RunConfig =
    { packageName : String
    , modulePath : String
    , ast : Parser.AST
................................................................................
                Nothing ->
                    Err <| UnknownTypeRef range name
    in
    case type_ of
        Parser.LocalRef "Int" [] ->
            Ok <| Type.Int

        Parser.LocalRef "Int" other ->
            Err <| BadIntType range (List.length other)

        Parser.LocalRef "Array" [ t ] ->
            case qualifyMemberType config modRefs range t of
                Err err ->
                    Err err

                Ok t_ ->
                    Ok <| Type.Array t_

        Parser.LocalRef "Array" other ->
            Err <| BadArrayType range (List.length other)

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

                Nothing ->
                    importsLookup name []
................................................................................

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

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

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

        Parser.TypeMatch range (Parser.LocalRef name []) patterns ->
            case qualifiedNameToMatch (qualifiedRange range) (qualifyName config name) patterns of
                (Err (UnknownTypeRef _ _)) as errMsg ->
................................................................................
                            Ok (FunctionRef (mapLoc sourceLocation) qualifiedFunction)
                                :: acc.qualifiedNodes
                        , inlineFunctionNames =
                            acc.inlineFunctionNames
                                |> Set.union qualifyNodeResult.inlineFunctionNames
                                |> Set.insert inlineFuncName
                    }

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

        Parser.ArrayLiteral loc [] ->
            { acc
                | qualifiedNodes =
                    Ok (Builtin (mapLoc loc) Builtin.ArrayEmpty)
                        :: acc.qualifiedNodes
            }

        Parser.ArrayLiteral loc nodes ->
            let
                qualifyNodeResult =
                    initQualifyNode
                        config
                        acc.qualifiedTypes
                        acc.qualifiedFunctions
                        currentDefName
                        acc.modRefs
                        acc.currentlyParsing
                        nodes
            in
            case qualifyNodeResult.qualifiedNodes of
                Ok qualifiedNodes ->
                    { acc
                        | qualifiedNodes =
                            Ok (ArrayLiteral (mapLoc loc) qualifiedNodes)
                                :: acc.qualifiedNodes
                    }

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


isMultiFunction : Parser.FunctionDefinition -> Bool
isMultiFunction def =

Modified src/Stabel/Qualifier/Problem.elm from [616702f68f] to [2744deccb7].

11
12
13
14
15
16
17


18
19
20
21
22
23
24
..
83
84
85
86
87
88
89




















90
91
92
93
94
95
96
...
107
108
109
110
111
112
113






    = UnknownFunctionRef SourceLocationRange String
    | UnknownTypeRef SourceLocationRange String
    | UnionTypeMatchWithPatterns SourceLocationRange
    | InvalidTypeMatch SourceLocationRange
    | NoSuchMemberOnType SourceLocationRange String String
    | FunctionNotExposed SourceLocationRange String
    | TypeNotExposed SourceLocationRange String




toString : String -> Problem -> String
toString source problem =
    case problem of
        UnknownFunctionRef range functionRef ->
            ">> "
................................................................................
                ++ "\n\n"
                ++ SourceLocation.extractFromString source range.start range.end
                ++ "\n\n"
                ++ "Referencing '"
                ++ typeRef
                ++ "' but this type is not exposed."






















sourceLocationRef : Problem -> String
sourceLocationRef problem =
    case problem of
        UnknownFunctionRef range _ ->
            range.source

................................................................................
            range.source

        FunctionNotExposed range _ ->
            range.source

        TypeNotExposed range _ ->
            range.source













>
>







 







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







 







>
>
>
>
>
>
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
..
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
...
129
130
131
132
133
134
135
136
137
138
139
140
141
    = UnknownFunctionRef SourceLocationRange String
    | UnknownTypeRef SourceLocationRange String
    | UnionTypeMatchWithPatterns SourceLocationRange
    | InvalidTypeMatch SourceLocationRange
    | NoSuchMemberOnType SourceLocationRange String String
    | FunctionNotExposed SourceLocationRange String
    | TypeNotExposed SourceLocationRange String
    | BadIntType SourceLocationRange Int
    | BadArrayType SourceLocationRange Int


toString : String -> Problem -> String
toString source problem =
    case problem of
        UnknownFunctionRef range functionRef ->
            ">> "
................................................................................
                ++ "\n\n"
                ++ SourceLocation.extractFromString source range.start range.end
                ++ "\n\n"
                ++ "Referencing '"
                ++ typeRef
                ++ "' but this type is not exposed."

        BadIntType range num ->
            ">> "
                ++ range.source
                ++ "\n\n"
                ++ SourceLocation.extractFromString source range.start range.end
                ++ "\n\n"
                ++ "An Int takes no type parameters, you've provided "
                ++ String.fromInt num
                ++ "."

        BadArrayType range num ->
            ">> "
                ++ range.source
                ++ "\n\n"
                ++ SourceLocation.extractFromString source range.start range.end
                ++ "\n\n"
                ++ "An Array requires exactly one type parameter, you've provided "
                ++ String.fromInt num
                ++ "."


sourceLocationRef : Problem -> String
sourceLocationRef problem =
    case problem of
        UnknownFunctionRef range _ ->
            range.source

................................................................................
            range.source

        FunctionNotExposed range _ ->
            range.source

        TypeNotExposed range _ ->
            range.source

        BadIntType range _ ->
            range.source

        BadArrayType range _ ->
            range.source

Modified src/Stabel/TypeChecker.elm from [2a153ab55d] to [ae014cff34].

8
9
10
11
12
13
14

15
16
17
18
19
20
21
..
53
54
55
56
57
58
59

60
61
62
63
64
65
66
...
261
262
263
264
265
266
267












268
269
270
271
272
273
274
...
305
306
307
308
309
310
311


































312
313
314
315
316
317
318
....
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
....
1313
1314
1315
1316
1317
1318
1319



1320
1321
1322
1323
1324
1325
1326
....
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
....
1547
1548
1549
1550
1551
1552
1553



1554
1555
1556






































1557
1558
1559
1560
1561
1562
1563
    , TypeMatch(..)
    , TypeMatchValue(..)
    , run
    )

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

import Set exposing (Set)
import Stabel.Data.Builtin as Builtin exposing (Builtin)
import Stabel.Data.SourceLocation as SourceLocation exposing (SourceLocationRange)
import Stabel.Data.Type as Type exposing (FunctionType, Type)
import Stabel.Data.TypeSignature as TypeSignature exposing (TypeSignature)
import Stabel.Qualifier as Qualifier
import Stabel.TypeChecker.Problem exposing (Problem(..))
................................................................................
    = LiteralInt Int
    | LiteralType Type
    | RecursiveMatch TypeMatch


type AstNode
    = IntLiteral SourceLocationRange Int

    | Function SourceLocationRange FunctionDefinition FunctionType
    | FunctionRef SourceLocationRange FunctionDefinition
    | Recurse SourceLocationRange
    | Cycle SourceLocationRange CycleData
    | Builtin SourceLocationRange Builtin
    | ConstructType TypeDefinition
    | SetMember TypeDefinition String Int Type
................................................................................

untypedToTypedNode : Int -> Context -> Qualifier.Node -> AstNode
untypedToTypedNode idx context untypedNode =
    case untypedNode of
        Qualifier.Integer range num ->
            IntLiteral range num













        Qualifier.Function range function ->
            let
                ( def, _ ) =
                    typeCheckDefinition function context
            in
            Function range def <|
                resolveGenericsInFunctionType idx context def.type_
................................................................................

        Qualifier.SetMember typeDef memberName memberIndex memberType ->
            SetMember typeDef memberName memberIndex memberType

        Qualifier.GetMember typeDef memberName memberIndex memberType ->
            GetMember typeDef memberName memberIndex memberType




































resolveGenericsInFunctionType : Int -> Context -> FunctionType -> FunctionType
resolveGenericsInFunctionType idx context wt =
    let
        replaceGenericWithBoundValue t =
            let
                boundType =
................................................................................

        Nothing ->
            context


typeCheckNode : Qualifier.FunctionDefinition -> Int -> Qualifier.Node -> Context -> Context
typeCheckNode currentDef idx node context =
    let

        addStackEffect ctx effects =
            { ctx | stackEffects = ctx.stackEffects ++ List.map (tagGenericEffect idx) effects }
    in







    case node of
        Qualifier.Integer _ _ ->
            addStackEffect context [ Push Type.Int ]











































































        Qualifier.Function _ untypedDef ->
            let
                ( def, contextWithTypedDef ) =
                    typeCheckDefinition untypedDef context

                newContext =
                    { contextWithTypedDef | stackEffects = context.stackEffects }
            in
            addStackEffect newContext <| functionTypeToStackEffects def.type_

        Qualifier.FunctionRef _ ref ->
            let
                stackEffectsBeforeFunctionCheck =
                    context.stackEffects

                ( def, contextAfterFunctionCheck ) =
                    typeCheckDefinition ref context

                newContext =
                    { contextAfterFunctionCheck | stackEffects = stackEffectsBeforeFunctionCheck }
            in

            addStackEffect newContext <|
                [ Push <| Type.FunctionSignature def.type_ ]


        Qualifier.Recurse _ ->
            case TypeSignature.toMaybe currentDef.typeSignature of
                Just annotatedType ->
                    addStackEffect context <| functionTypeToStackEffects annotatedType

                Nothing ->
                    let
                        problem =

                            MissingTypeAnnotationInRecursiveCallStack
                                (Maybe.withDefault SourceLocation.emptyRange currentDef.sourceLocation)
                                currentDef.name
                    in
                    { context | errors = problem :: context.errors }

        Qualifier.Cycle _ data ->
            case TypeSignature.toMaybe data.typeSignature of
                Just annotatedType ->
                    addStackEffect context <| functionTypeToStackEffects annotatedType

                Nothing ->
                    let
                        problem =

                            MissingTypeAnnotationInRecursiveCallStack
                                (Maybe.withDefault SourceLocation.emptyRange data.sourceLocation)
                                data.name
                    in
                    { context | errors = problem :: context.errors }

        Qualifier.ConstructType typeDef ->
            let
                memberTypes =
                    getStructMembers typeDef
                        |> List.map Tuple.second

                typeInQuestion =
                    getStructType typeDef
            in

            addStackEffect context <|
                functionTypeToStackEffects
                    { input = memberTypes
                    , output = [ typeInQuestion ]
                    }


        Qualifier.SetMember typeDef _ _ memberType ->
            let
                typeInQuestion =
                    getStructType typeDef
            in

            addStackEffect context <|
                functionTypeToStackEffects
                    { input = [ typeInQuestion, memberType ]
                    , output = [ typeInQuestion ]
                    }


        Qualifier.GetMember typeDef _ _ memberType ->
            let
                typeInQuestion =
                    getStructType typeDef
            in

            addStackEffect context <|
                functionTypeToStackEffects
                    { input = [ typeInQuestion ]
                    , output = [ memberType ]
                    }


        Qualifier.Builtin _ builtin ->


            addStackEffect context <| functionTypeToStackEffects <| Builtin.functionType builtin




































getStructMembers : TypeDefinition -> List ( String, Type )
getStructMembers typeDef =
    case typeDef.members of
        Qualifier.StructMembers members ->
            members
................................................................................

        Type.FunctionSignature wt ->
            Type.FunctionSignature
                { input = List.map (tagGeneric idx) wt.input
                , output = List.map (tagGeneric idx) wt.output
                }




        _ ->
            type_


functionTypeToStackEffects : FunctionType -> List StackEffect
functionTypeToStackEffects functionType =
    List.map Pop (List.reverse functionType.input)
................................................................................
        ( Just boundA, Just boundB ) ->
            if boundA == boundB then
                ( context, True )

            else
                case ( boundA, boundB ) of
                    ( Type.Union _ leftUnion, Type.Union _ rightUnion ) ->
                        -- TODO: Requires unions to be sorted in same order
                        let

                            lengthTest =
                                List.length leftUnion == List.length rightUnion

                            ( newContext, allMembersTest ) =
                                List.map2 Tuple.pair leftUnion rightUnion
                                    |> List.foldl foldHelper ( context, True )

                            foldHelper ( lType, rType ) ( ctx, currValue ) =
                                if not currValue then
                                    ( ctx, currValue )

                                else
                                    compatibleTypes ctx lType rType
                        in
                        ( newContext
                        , lengthTest && allMembersTest
                        )

                    ( Type.Union _ unionTypes, rhs ) ->
                        -- Cannot normally go from union to concrete type
................................................................................
                                else
                                    compatibleTypes currCtx lType rType
                        in
                        ( contextAfterOutputCheck
                        , inputsCompatible && outputsCompatible
                        )




                    _ ->
                        ( context, False )








































getGenericBinding : Context -> Type -> Maybe Type
getGenericBinding context type_ =
    case type_ of
        Type.Generic genericId ->
            case Dict.get genericId context.boundGenerics of
                Just (Type.Generic nextGenericId) ->







>







 







>







 







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







 







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







 







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


|

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








|












>
|
|
>




|


<
<
>
|
|
|
<
<




|


<
<
>
|
|
|
<
<










>
|
|



>






>
|
|



>






>
|
|



|
>

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







 







>
>
>







 







<

>




|
<
<
<
<
<
<
<
<







 







>
>
>



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







8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
..
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
...
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
...
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
....
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
....
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
....
1596
1597
1598
1599
1600
1601
1602

1603
1604
1605
1606
1607
1608
1609








1610
1611
1612
1613
1614
1615
1616
....
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
    , TypeMatch(..)
    , TypeMatchValue(..)
    , run
    )

import Dict exposing (Dict)
import List.Extra as List
import Result.Extra as Result
import Set exposing (Set)
import Stabel.Data.Builtin as Builtin exposing (Builtin)
import Stabel.Data.SourceLocation as SourceLocation exposing (SourceLocationRange)
import Stabel.Data.Type as Type exposing (FunctionType, Type)
import Stabel.Data.TypeSignature as TypeSignature exposing (TypeSignature)
import Stabel.Qualifier as Qualifier
import Stabel.TypeChecker.Problem exposing (Problem(..))
................................................................................
    = LiteralInt Int
    | LiteralType Type
    | RecursiveMatch TypeMatch


type AstNode
    = IntLiteral SourceLocationRange Int
    | ArrayLiteral SourceLocationRange (List AstNode) Type
    | Function SourceLocationRange FunctionDefinition FunctionType
    | FunctionRef SourceLocationRange FunctionDefinition
    | Recurse SourceLocationRange
    | Cycle SourceLocationRange CycleData
    | Builtin SourceLocationRange Builtin
    | ConstructType TypeDefinition
    | SetMember TypeDefinition String Int Type
................................................................................

untypedToTypedNode : Int -> Context -> Qualifier.Node -> AstNode
untypedToTypedNode idx context untypedNode =
    case untypedNode of
        Qualifier.Integer range num ->
            IntLiteral range num

        Qualifier.ArrayLiteral range nodes ->
            let
                typedNodes =
                    List.map (untypedToTypedNode idx context) nodes

                arrayType =
                    List.filterMap arrayNodeToType typedNodes
                        |> unionizeTypes
                        |> Type.Array
            in
            ArrayLiteral range typedNodes arrayType

        Qualifier.Function range function ->
            let
                ( def, _ ) =
                    typeCheckDefinition function context
            in
            Function range def <|
                resolveGenericsInFunctionType idx context def.type_
................................................................................

        Qualifier.SetMember typeDef memberName memberIndex memberType ->
            SetMember typeDef memberName memberIndex memberType

        Qualifier.GetMember typeDef memberName memberIndex memberType ->
            GetMember typeDef memberName memberIndex memberType


arrayNodeToType : AstNode -> Maybe Type
arrayNodeToType n =
    case n of
        IntLiteral _ _ ->
            Just Type.Int

        ArrayLiteral _ _ t ->
            Just t

        Function _ _ t ->
            List.head t.output

        FunctionRef _ def ->
            Just <| Type.FunctionSignature def.type_

        Recurse _ ->
            Nothing

        Cycle _ data ->
            List.head data.typeSignature.output

        Builtin _ _ ->
            Nothing

        ConstructType _ ->
            Nothing

        SetMember _ _ _ _ ->
            Nothing

        GetMember _ _ _ _ ->
            Nothing


resolveGenericsInFunctionType : Int -> Context -> FunctionType -> FunctionType
resolveGenericsInFunctionType idx context wt =
    let
        replaceGenericWithBoundValue t =
            let
                boundType =
................................................................................

        Nothing ->
            context


typeCheckNode : Qualifier.FunctionDefinition -> Int -> Qualifier.Node -> Context -> Context
typeCheckNode currentDef idx node context =
    case nodeToStackEffect currentDef node context of
        Ok ( newContext, effects ) ->
            addStackEffect newContext idx effects



        Err error ->
            { context | errors = error :: context.errors }


nodeToStackEffect : Qualifier.FunctionDefinition -> Qualifier.Node -> Context -> Result Problem ( Context, List StackEffect )
nodeToStackEffect currentDef node context =
    case node of
        Qualifier.Integer _ _ ->
            Ok ( context, [ Push Type.Int ] )

        Qualifier.ArrayLiteral loc nodes ->
            let
                res =
                    List.foldr
                        (\n acc ->
                            case acc of
                                Err _ ->
                                    acc

                                Ok ( previousStackEffects, previousContext ) ->
                                    case nodeToStackEffect currentDef n previousContext of
                                        Err err ->
                                            Err err

                                        Ok ( nextContext, nodeStackEffects ) ->
                                            Ok ( nodeStackEffects :: previousStackEffects, nextContext )
                        )
                        (Ok ( [], context ))
                        nodes
                        |> Result.map (Tuple.mapFirst (List.map effectsToFunctionType))
                        |> Result.map (Tuple.mapFirst (List.map validateArrayType))
                        |> Result.map (Tuple.mapFirst Result.combine)
                        |> Result.andThen liftTupleFirstResult
                        |> Result.map (Tuple.mapFirst (List.concatMap .output))
                        |> Result.map (Tuple.mapFirst unionizeTypes)

                effectsToFunctionType effects =
                    let
                        ( inputs, outputs ) =
                            List.partition stackEffectIsPop effects
                                |> Tuple.mapBoth (List.map stackEffectType) (List.map stackEffectType)
                    in
                    { input = inputs
                    , output = outputs
                    }

                stackEffectIsPop effect =
                    case effect of
                        Pop _ ->
                            True

                        Push _ ->
                            False

                stackEffectType effect =
                    case effect of
                        Pop t ->
                            t

                        Push t ->
                            t

                validateArrayType type_ =
                    if List.isEmpty type_.input && List.length type_.output == 1 then
                        Ok type_

                    else
                        Err <| BadArrayElement loc type_

                liftTupleFirstResult ( resA, b ) =
                    case resA of
                        Ok a ->
                            Ok ( a, b )

                        Err err ->
                            Err err
            in
            case res of
                Ok ( inferredType, newContext ) ->
                    Ok ( newContext, [ Push <| Type.Array inferredType ] )

                Err err ->
                    Err err

        Qualifier.Function _ untypedDef ->
            let
                ( def, contextWithTypedDef ) =
                    typeCheckDefinition untypedDef context

                newContext =
                    { contextWithTypedDef | stackEffects = context.stackEffects }
            in
            Ok ( newContext, functionTypeToStackEffects def.type_ )

        Qualifier.FunctionRef _ ref ->
            let
                stackEffectsBeforeFunctionCheck =
                    context.stackEffects

                ( def, contextAfterFunctionCheck ) =
                    typeCheckDefinition ref context

                newContext =
                    { contextAfterFunctionCheck | stackEffects = stackEffectsBeforeFunctionCheck }
            in
            Ok
                ( newContext
                , [ Push <| Type.FunctionSignature def.type_ ]
                )

        Qualifier.Recurse _ ->
            case TypeSignature.toMaybe currentDef.typeSignature of
                Just annotatedType ->
                    Ok ( context, functionTypeToStackEffects annotatedType )

                Nothing ->


                    Err <|
                        MissingTypeAnnotationInRecursiveCallStack
                            (Maybe.withDefault SourceLocation.emptyRange currentDef.sourceLocation)
                            currentDef.name



        Qualifier.Cycle _ data ->
            case TypeSignature.toMaybe data.typeSignature of
                Just annotatedType ->
                    Ok ( context, functionTypeToStackEffects annotatedType )

                Nothing ->


                    Err <|
                        MissingTypeAnnotationInRecursiveCallStack
                            (Maybe.withDefault SourceLocation.emptyRange data.sourceLocation)
                            data.name



        Qualifier.ConstructType typeDef ->
            let
                memberTypes =
                    getStructMembers typeDef
                        |> List.map Tuple.second

                typeInQuestion =
                    getStructType typeDef
            in
            Ok
                ( context
                , functionTypeToStackEffects
                    { input = memberTypes
                    , output = [ typeInQuestion ]
                    }
                )

        Qualifier.SetMember typeDef _ _ memberType ->
            let
                typeInQuestion =
                    getStructType typeDef
            in
            Ok
                ( context
                , functionTypeToStackEffects
                    { input = [ typeInQuestion, memberType ]
                    , output = [ typeInQuestion ]
                    }
                )

        Qualifier.GetMember typeDef _ _ memberType ->
            let
                typeInQuestion =
                    getStructType typeDef
            in
            Ok
                ( context
                , functionTypeToStackEffects
                    { input = [ typeInQuestion ]
                    , output = [ memberType ]
                    }
                )

        Qualifier.Builtin _ builtin ->
            Ok
                ( context
                , functionTypeToStackEffects <|
                    Builtin.functionType builtin
                )


addStackEffect : Context -> Int -> List StackEffect -> Context
addStackEffect ctx idx effects =
    { ctx | stackEffects = ctx.stackEffects ++ List.map (tagGenericEffect idx) effects }


unionizeTypes : List Type -> Type
unionizeTypes ts =
    unionizeTypesHelper ts []


unionizeTypesHelper : List Type -> List Type -> Type
unionizeTypesHelper ts acc =
    case ts of
        [] ->
            case acc of
                [] ->
                    Type.Generic "a"

                [ t ] ->
                    t

                _ ->
                    Type.Union Nothing acc

        t :: rest ->
            if List.member t acc then
                unionizeTypesHelper rest acc

            else
                unionizeTypesHelper rest (t :: acc)


getStructMembers : TypeDefinition -> List ( String, Type )
getStructMembers typeDef =
    case typeDef.members of
        Qualifier.StructMembers members ->
            members
................................................................................

        Type.FunctionSignature wt ->
            Type.FunctionSignature
                { input = List.map (tagGeneric idx) wt.input
                , output = List.map (tagGeneric idx) wt.output
                }

        Type.Array t ->
            Type.Array <| tagGeneric idx t

        _ ->
            type_


functionTypeToStackEffects : FunctionType -> List StackEffect
functionTypeToStackEffects functionType =
    List.map Pop (List.reverse functionType.input)
................................................................................
        ( Just boundA, Just boundB ) ->
            if boundA == boundB then
                ( context, True )

            else
                case ( boundA, boundB ) of
                    ( Type.Union _ leftUnion, Type.Union _ rightUnion ) ->

                        let
                            -- TODO: lift this restriction in the future?
                            lengthTest =
                                List.length leftUnion == List.length rightUnion

                            ( newContext, allMembersTest ) =
                                subList leftUnion rightUnion context








                        in
                        ( newContext
                        , lengthTest && allMembersTest
                        )

                    ( Type.Union _ unionTypes, rhs ) ->
                        -- Cannot normally go from union to concrete type
................................................................................
                                else
                                    compatibleTypes currCtx lType rType
                        in
                        ( contextAfterOutputCheck
                        , inputsCompatible && outputsCompatible
                        )

                    ( Type.Array lt, Type.Array rt ) ->
                        compatibleTypes context lt rt

                    _ ->
                        ( context, False )


{-| Is the first list a subset of the second?
-}
subList : List Type -> List Type -> Context -> ( Context, Bool )
subList lhs rhs ctx =
    case lhs of
        [] ->
            ( ctx, True )

        first :: rest ->
            case findMap (compatibleTypes ctx first) Tuple.second rhs of
                Just ( rhsType, ( newContext, _ ) ) ->
                    subList
                        rest
                        (List.filter ((/=) rhsType) rest)
                        newContext

                Nothing ->
                    ( ctx, False )


findMap : (a -> b) -> (b -> Bool) -> List a -> Maybe ( a, b )
findMap mapFn predFn ls =
    case ls of
        [] ->
            Nothing

        first :: rest ->
            let
                mapped =
                    mapFn first
            in
            if predFn mapped then
                Just ( first, mapped )

            else
                findMap mapFn predFn rest


getGenericBinding : Context -> Type -> Maybe Type
getGenericBinding context type_ =
    case type_ of
        Type.Generic genericId ->
            case Dict.get genericId context.boundGenerics of
                Just (Type.Generic nextGenericId) ->

Modified src/Stabel/TypeChecker/Problem.elm from [f356902d82] to [541dc50bc8].

12
13
14
15
16
17
18

19
20
21
22
23
24
25
..
99
100
101
102
103
104
105










106
107
108
109
110
111
112
...
123
124
125
126
127
128
129



    = UndeclaredGeneric SourceLocationRange String
    | TypeError SourceLocationRange String FunctionType FunctionType
    | UnexpectedType SourceLocationRange String Type Type
    | InconsistentWhens SourceLocationRange String
    | MissingTypeAnnotationInRecursiveCallStack SourceLocationRange String
    | InexhaustiveMultiFunction SourceLocationRange (List (List Type))
    | BadEntryPoint SourceLocationRange String FunctionType FunctionType



toString : String -> Problem -> String
toString source problem =
    case problem of
        UndeclaredGeneric range generic ->
            ">> "
................................................................................
                ++ "In order to be called from the command line, the type of '"
                ++ name
                ++ "' needs to be:\n\n"
                ++ Type.functionTypeToString actual
                ++ "\n\nHowever, it seems that the actual type is:\n\n"
                ++ Type.functionTypeToString expected












sourceLocationRef : Problem -> String
sourceLocationRef problem =
    case problem of
        UndeclaredGeneric range _ ->
            range.source

................................................................................
            range.source

        InexhaustiveMultiFunction range _ ->
            range.source

        BadEntryPoint range _ _ _ ->
            range.source










>







 







>
>
>
>
>
>
>
>
>
>







 







>
>
>
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
...
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
...
134
135
136
137
138
139
140
141
142
143
    = UndeclaredGeneric SourceLocationRange String
    | TypeError SourceLocationRange String FunctionType FunctionType
    | UnexpectedType SourceLocationRange String Type Type
    | InconsistentWhens SourceLocationRange String
    | MissingTypeAnnotationInRecursiveCallStack SourceLocationRange String
    | InexhaustiveMultiFunction SourceLocationRange (List (List Type))
    | BadEntryPoint SourceLocationRange String FunctionType FunctionType
    | BadArrayElement SourceLocationRange FunctionType


toString : String -> Problem -> String
toString source problem =
    case problem of
        UndeclaredGeneric range generic ->
            ">> "
................................................................................
                ++ "In order to be called from the command line, the type of '"
                ++ name
                ++ "' needs to be:\n\n"
                ++ Type.functionTypeToString actual
                ++ "\n\nHowever, it seems that the actual type is:\n\n"
                ++ Type.functionTypeToString expected

        BadArrayElement range actual ->
            ">> "
                ++ range.source
                ++ "\n\n"
                ++ SourceLocation.extractFromString source range.start range.end
                ++ "\n\n"
                ++ "An Array can only contain elements of type ( -- a ), but found an element with type:"
                ++ "\n\n"
                ++ Type.functionTypeToString actual


sourceLocationRef : Problem -> String
sourceLocationRef problem =
    case problem of
        UndeclaredGeneric range _ ->
            range.source

................................................................................
            range.source

        InexhaustiveMultiFunction range _ ->
            range.source

        BadEntryPoint range _ _ _ ->
            range.source

        BadArrayElement range _ ->
            range.source

Modified src/Stabel/Wasm.elm from [3afad62349] to [f1b8bdee1a].

75
76
77
78
79
80
81

82
83
84
85
86
87
88
..
91
92
93
94
95
96
97


98
99
100

101
102
103
104
105
106
107
...
350
351
352
353
354
355
356


















357
358
359
360
361
362
363
...
398
399
400
401
402
403
404






405
406
407
408
409
410
411
...
415
416
417
418
419
420
421



422
423
424
425
426
427
428

type Instruction
    = Batch (List Instruction)
    | Block (List Instruction)
    | Loop (List Instruction)
    | Break Int
    | BreakIf Int

    | Return
    | Call Int String
    | CallIndirect
    | Local_Get Int
    | Local_Set Int
    | Local_Tee Int
    | I32_Const Int
................................................................................
    | I32_Mul
    | I32_Div
    | I32_Eq
    | I32_NotEq
    | I32_EqZero
    | I32_Store
    | I32_Load


    | Drop
    | Unreachable
    | Commented String Instruction



maximumLocalIndex : Instruction -> Maybe Int
maximumLocalIndex ins =
    case ins of
        Batch insList ->
            List.filterMap maximumLocalIndex insList
................................................................................

        Break num ->
            Str <| "(br " ++ String.fromInt num ++ ")"

        BreakIf num ->
            Str <| "(br_if " ++ String.fromInt num ++ ")"



















        Return ->
            Str "return"

        Call id fnName ->
            Str <| "(call " ++ String.fromInt id ++ ") ;; $" ++ fnName

        CallIndirect ->
................................................................................

        I32_Store ->
            Str "i32.store"

        I32_Load ->
            Str "i32.load"







        Drop ->
            Str "drop"

        Unreachable ->
            Str "unreachable"

        Commented comment inst ->
................................................................................

                BatchFormat batch ->
                    BatchFormat <| (Str <| ";; " ++ comment) :: batch

                Indent batch ->
                    Indent <| (Str <| ";; " ++ comment) :: batch





formatExport : ( String, Int ) -> FormatHint
formatExport ( functionName, index ) =
    Str <|
        "(export \""
            ++ functionName
            ++ "\" (func "







>







 







>
>



>







 







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







 







>
>
>
>
>
>







 







>
>
>







75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
..
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
...
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
...
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
...
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459

type Instruction
    = Batch (List Instruction)
    | Block (List Instruction)
    | Loop (List Instruction)
    | Break Int
    | BreakIf Int
    | If (List Instruction) (List Instruction)
    | Return
    | Call Int String
    | CallIndirect
    | Local_Get Int
    | Local_Set Int
    | Local_Tee Int
    | I32_Const Int
................................................................................
    | I32_Mul
    | I32_Div
    | I32_Eq
    | I32_NotEq
    | I32_EqZero
    | I32_Store
    | I32_Load
    | I32_LT
    | I32_GTE
    | Drop
    | Unreachable
    | Commented String Instruction
    | Memory_Copy


maximumLocalIndex : Instruction -> Maybe Int
maximumLocalIndex ins =
    case ins of
        Batch insList ->
            List.filterMap maximumLocalIndex insList
................................................................................

        Break num ->
            Str <| "(br " ++ String.fromInt num ++ ")"

        BreakIf num ->
            Str <| "(br_if " ++ String.fromInt num ++ ")"

        If thenIns elseIns ->
            if List.isEmpty elseIns then
                BatchFormat
                    [ Str "(if (then"
                    , Indent <| List.map formatInstruction thenIns
                    , Str "))"
                    ]

            else
                BatchFormat
                    [ Str "(if (then"
                    , Indent <| List.map formatInstruction thenIns
                    , Str ")"
                    , Str "(else"
                    , Indent <| List.map formatInstruction elseIns
                    , Str "))"
                    ]

        Return ->
            Str "return"

        Call id fnName ->
            Str <| "(call " ++ String.fromInt id ++ ") ;; $" ++ fnName

        CallIndirect ->
................................................................................

        I32_Store ->
            Str "i32.store"

        I32_Load ->
            Str "i32.load"

        I32_LT ->
            Str "i32.lt_s"

        I32_GTE ->
            Str "i32.ge_s"

        Drop ->
            Str "drop"

        Unreachable ->
            Str "unreachable"

        Commented comment inst ->
................................................................................

                BatchFormat batch ->
                    BatchFormat <| (Str <| ";; " ++ comment) :: batch

                Indent batch ->
                    Indent <| (Str <| ";; " ++ comment) :: batch

        Memory_Copy ->
            Str "memory.copy"


formatExport : ( String, Int ) -> FormatHint
formatExport ( functionName, index ) =
    Str <|
        "(export \""
            ++ functionName
            ++ "\" (func "

Modified test_expression.js from [38206c5380] to [284ab87777].




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



const compiler = require('./wasm_tests/compiler.wrapper');
const wabt = require('wabt')();

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

global.memView = new Uint32Array(memory.buffer, 0, 512);

async function init() {

    const wat = await compiler.toWat(`
        deftype: Box
        : { value: Int }

        deftype: BoxOfBox
        : { box: Box }

        defmulti: deep-one?
        when: BoxOfBox( box Box( value 1 ) )
          drop 1
        : drop 0

        def: main
        entry: true
        : 1 >Box >BoxOfBox deep-one?



    `);

    const wasmModule = wabt.parseWat('tmp', wat).toBinary({}).buffer;



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

    const program = await WebAssembly.instantiate(wasmModule, imports);
    debugger;
    program.instance.exports.main();
}

init();
>
>
>

|








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

<
<
>
>
>


|
>
>








<




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
// Execute with: node --inspect-brk ./test_expression.js
// Then open chrome and go to: chrome://inspect

const compiler = require('./wasm_tests/compiler.wrapper');
const wabtInit = require('wabt');

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

global.memView = new Uint32Array(memory.buffer, 0, 512);

async function init() {
    const wabt = await wabtInit();
    const wat = await compiler.toWat('main', `











        def: main


        : { 5 6 7 }
          1 array-get
          swap drop
    `);

    const wasmModule = wabt.parseWat('tmp', wat, {
        bulk_memory: true
    }).toBinary({}).buffer;

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

    const program = await WebAssembly.instantiate(wasmModule, imports);

    program.instance.exports.main();
}

init();

Modified tests/Test/Parser.elm from [736941670b] to [7f783df7cb].

891
892
893
894
895
896
897









































898
899
900
901
902
903
904
                                                [ AST.Function emptyRange "False" ]
                                      }
                                    ]
                            }
                    in
                    expectAst source expectedAst
            ]









































        , test "Definition without implementation should be legal" <|
            \_ ->
                expectCompiles
                    """
                    def: somefunc
                    """
        , test "Support code comments" <|







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







891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
                                                [ AST.Function emptyRange "False" ]
                                      }
                                    ]
                            }
                    in
                    expectAst source expectedAst
            ]
        , test "Array" <|
            \_ ->
                let
                    source =
                        """
                        def: some-array
                        : { 1 2 /ext/func fn 5 { 1 2 } }
                        """

                    expectedAst =
                        { sourceReference = ""
                        , moduleDefinition = ModuleDefinition.Undefined
                        , types = Dict.empty
                        , functions =
                            Dict.fromListBy .name
                                [ { name = "some-array"
                                  , typeSignature = AssociatedFunctionSignature.NotProvided
                                  , sourceLocationRange = Nothing
                                  , aliases = Dict.empty
                                  , imports = Dict.empty
                                  , implementation =
                                        SoloImpl
                                            [ AST.ArrayLiteral emptyRange
                                                [ AST.Integer emptyRange 1
                                                , AST.Integer emptyRange 2
                                                , AST.ExternalFunction emptyRange
                                                    [ "ext" ]
                                                    "func"
                                                , AST.Function emptyRange "fn"
                                                , AST.Integer emptyRange 5
                                                , AST.ArrayLiteral emptyRange
                                                    [ AST.Integer emptyRange 1
                                                    , AST.Integer emptyRange 2
                                                    ]
                                                ]
                                            ]
                                  }
                                ]
                        }
                in
                expectAst source expectedAst
        , test "Definition without implementation should be legal" <|
            \_ ->
                expectCompiles
                    """
                    def: somefunc
                    """
        , test "Support code comments" <|

Modified tests/Test/Parser/Util.elm from [6df7bbdd46] to [38c3a75d10].

78
79
80
81
82
83
84



85
86
87
88
89
90
91

        AST.ExternalFunction _ path val ->
            AST.ExternalFunction emptyRange path val

        AST.InlineFunction _ val ->
            AST.InlineFunction emptyRange (List.map stripNodeLocation val)




        _ ->
            node


stripMultiWordBranchLocation : ( TypeMatch, List AstNode ) -> ( TypeMatch, List AstNode )
stripMultiWordBranchLocation ( typeMatch, nodes ) =
    ( stripTypeMatchLocation typeMatch







>
>
>







78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

        AST.ExternalFunction _ path val ->
            AST.ExternalFunction emptyRange path val

        AST.InlineFunction _ val ->
            AST.InlineFunction emptyRange (List.map stripNodeLocation val)

        AST.ArrayLiteral _ val ->
            AST.ArrayLiteral emptyRange (List.map stripNodeLocation val)

        _ ->
            node


stripMultiWordBranchLocation : ( TypeMatch, List AstNode ) -> ( TypeMatch, List AstNode )
stripMultiWordBranchLocation ( typeMatch, nodes ) =
    ( stripTypeMatchLocation typeMatch

Modified tests/Test/Qualifier/Errors.elm from [904e91d942] to [5ffe1b5acb].

71
72
73
74
75
76
77






































































78
79
80
81
82
83
84
                            """
                            defstruct: BoxWrapper
                            : box Box
                            """
                    in
                    checkForError (noSuchTypeReferenceError "Box") source
            ]






































































        ]


noSuchWordReferenceError : String -> Problem -> Bool
noSuchWordReferenceError name problem =
    case problem of
        UnknownFunctionRef _ problemName ->







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







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
                            """
                            defstruct: BoxWrapper
                            : box Box
                            """
                    in
                    checkForError (noSuchTypeReferenceError "Box") source
            ]
        , test "Wrong reference within array literal" <|
            \_ ->
                let
                    source =
                        """
                        def: main
                        : { one two }

                        def: one
                        : 1
                        """
                in
                checkForError (noSuchWordReferenceError "two") source
        , test "Bad Int type" <|
            \_ ->
                let
                    source =
                        """
                        def: main
                        type: -- (Int a)
                        : 1
                        """

                    badIntError problem =
                        case problem of
                            BadIntType _ 1 ->
                                True

                            _ ->
                                False
                in
                checkForError badIntError source
        , test "Bad Array type" <|
            \_ ->
                let
                    source =
                        """
                        def: main
                        type: -- (Array a b)
                        : { 1 { 2 } }
                        """

                    badArrayError problem =
                        case problem of
                            BadArrayType _ 2 ->
                                True

                            _ ->
                                False
                in
                checkForError badArrayError source
        , test "Bad Array type (no arguments)" <|
            \_ ->
                let
                    source =
                        """
                        def: main
                        type: -- Array
                        : { 1 2 }
                        """

                    badArrayError problem =
                        case problem of
                            BadArrayType _ 0 ->
                                True

                            _ ->
                                False
                in
                checkForError badArrayError source
        ]


noSuchWordReferenceError : String -> Problem -> Bool
noSuchWordReferenceError name problem =
    case problem of
        UnknownFunctionRef _ problemName ->

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

146
147
148
149
150
151
152



153
154
155
156
157
158
159

        AST.GetMember td n i t ->
            AST.GetMember (stripTypeLocation td) n i t

        AST.SetMember td n i t ->
            AST.SetMember (stripTypeLocation td) n i t





stripMultiWordBranchLocation : ( TypeMatch, List Node ) -> ( TypeMatch, List Node )
stripMultiWordBranchLocation ( typeMatch, nodes ) =
    ( stripTypeMatchLocation typeMatch
    , List.map stripNodeLocation nodes
    )








>
>
>







146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

        AST.GetMember td n i t ->
            AST.GetMember (stripTypeLocation td) n i t

        AST.SetMember td n i t ->
            AST.SetMember (stripTypeLocation td) n i t

        AST.ArrayLiteral _ nodes ->
            AST.ArrayLiteral emptyRange nodes


stripMultiWordBranchLocation : ( TypeMatch, List Node ) -> ( TypeMatch, List Node )
stripMultiWordBranchLocation ( typeMatch, nodes ) =
    ( stripTypeMatchLocation typeMatch
    , List.map stripNodeLocation nodes
    )

Added wasm_tests/array.test.js version [f6c84686e8].

























































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
const compiler = require('./compiler.wrapper');

test('Empty', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : {} array-length
    `);

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

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

test('Simple literal', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 1 2 3 4 5 } array-length
    `);

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

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

test('Literal with function reference', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 1 five 3 } array-length

        def: five
        : 5
    `);

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

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

test('Pushing', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : {}
          2 array-push
          1 array-push
          array-length
    `);

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

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

test('Get first', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 5 6 7 }
          0 array-get
          swap drop
    `);

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

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

test('Get second', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 5 6 7 }
          1 array-get
          swap drop
    `);

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

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

test('Get last', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 5 6 7 }
          2 array-get
          swap drop
    `);

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

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

test('Get function value', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 5 six 7 }
          1 array-get
          swap drop

        def: six
        : 6
    `);

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

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

test('Get succeess', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 5 6 7 }
          1 array-get
          drop
    `);

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

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

test('Get out of lower bound', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 5 6 7 }
          0 1 -
          array-get
          drop
    `);

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

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

test('Set works', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        : { 5 6 7 8 }
          20
          2 array-set
          2 array-get
          swap drop
    `);

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

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

test('Type annotation', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        type: -- Int
        : { 5 6 7 8 } array-length
    `);

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

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

test('Type tightening', async () => {
    const wat = await compiler.toWat('main', `
        def: main
        type: -- Int
        : empty array-length

        def: empty
        type: -- (Array Int)
        : {}
    `);

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

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

test('Pattern match', async () => {
    const wat = await compiler.toWat('main', `
        defunion: Test
        : Int
        : Array Int

        def: main
        type: -- Int
        : { 5 { 1 2 3 } }
          1 array-get
          swap drop
          to-num

        defmulti: to-num
        type: Test -- Int
        : Int
          # do nothing
        : Array
          array-length
    `);

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

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

test('Pattern match (reverse case)', async () => {
    const wat = await compiler.toWat('main', `
        defunion: Test
        : Int
        : Array Int

        def: main
        type: -- Int
        : { 5 { 1 2 3 } }
          0 array-get
          swap drop
          to-num

        defmulti: to-num
        type: Test -- Int
        : Int
          # do nothing
        : Array
          array-length
    `);

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

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

test('Pattern match (simple)', async () => {
    const wat = await compiler.toWat('main', `
        defunion: Test
        : Int
        : Array Int

        def: main
        type: -- Int
        : { 1 2 3 }
          to-num

        defmulti: to-num
        type: Test -- Int
        : Int
          # do nothing
        : Array
          array-length
    `);

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

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

Modified wasm_tests/compiler.wrapper.js from [527b014945] to [897ec18e2b].

51
52
53
54
55
56
57
58


59
60
61
62
63
64
65
            }
        });
    });
}

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



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

    const imports = {
        host: {







|
>
>







51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
            }
        });
    });
}

exports.run = async function run(wat, functionName) {
    const wabt = await wabtInit();
    const wasmModule = wabt.parseWat('tmp', wat, {
        bulk_memory: true
    }).toBinary({}).buffer;

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

    const imports = {
        host: {