aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/tool/compiler/language/lux/phase/analysis/case/coverage.lux
blob: 70623af8ab5ea5018de82b94e72578612baa453a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
(.module:
  [library
   [lux {"-" [Variant]}
    [abstract
     equivalence
     ["[0]" monad {"+" [do]}]]
    [control
     ["[0]" maybe]
     ["[0]" try {"+" [Try]} ("[1]\[0]" monad)]
     ["[0]" exception {"+" [exception:]}]]
    [data
     ["[0]" bit ("[1]\[0]" equivalence)]
     ["[0]" text
      ["%" format {"+" [Format format]}]]
     [collection
      ["[0]" list ("[1]\[0]" functor mix)]
      ["[0]" dictionary {"+" [Dictionary]}]]]
    [math
     [number
      ["n" nat]]]]]
  ["[0]" //// "_"
   [//
    ["/" analysis {"+" [Pattern Variant Operation]}]
    [///
     ["[1]" phase ("[1]\[0]" monad)]]]])

(exception: .public invalid_tuple_pattern
  "Tuple size must be >= 2")

(def: cases
  (-> (Maybe Nat) Nat)
  (|>> (maybe.else 0)))

(def: known_cases?
  (-> Nat Bit)
  (n.> 0))

... The coverage of a pattern-matching expression summarizes how well
... all the possible values of an input are being covered by the
... different patterns involved.
... Ideally, the pattern-matching has "exhaustive" coverage, which just
... means that every possible value can be matched by at least 1
... pattern.
... Every other coverage is considered partial, and it would be valued
... as insuficient (since it could lead to runtime errors due to values
... not being handled by any pattern).
... The #Partial tag covers arbitrary partial coverages in a general
... way, while the other tags cover more specific cases for bits
... and variants.
(type: .public Coverage
  (Rec Coverage
    (.Variant
     #Partial
     {#Bit Bit}
     {#Variant (Maybe Nat) (Dictionary Nat Coverage)}
     {#Seq Coverage Coverage}
     {#Alt Coverage Coverage}
     #Exhaustive)))

(def: .public (exhaustive? coverage)
  (-> Coverage Bit)
  (case coverage
    {#Exhaustive _}
    #1

    _
    #0))

(def: .public (%coverage value)
  (Format Coverage)
  (case value
    #Partial
    "#Partial"
    
    {#Bit value'}
    (|> value'
        %.bit
        (text.enclosed ["{#Bit " "}"]))
    
    {#Variant ?max_cases cases}
    (|> cases
        dictionary.entries
        (list\each (function (_ [idx coverage])
                     (format (%.nat idx) " " (%coverage coverage))))
        (text.interposed " ")
        (text.enclosed ["{" "}"])
        (format (%.nat (..cases ?max_cases)) " ")
        (text.enclosed ["{#Variant " "}"]))

    {#Seq left right}
    (format "{#Seq " (%coverage left) " " (%coverage right) "}")
    
    {#Alt left right}
    (format "{#Alt " (%coverage left) " " (%coverage right) "}")

    #Exhaustive
    "#Exhaustive"))

(def: .public (determine pattern)
  (-> Pattern (Operation Coverage))
  (case pattern
    (^or {#/.Simple #/.Unit}
         {#/.Bind _})
    (////\in #Exhaustive)

    ... Primitive patterns always have partial coverage because there
    ... are too many possibilities as far as values go.
    (^template [<tag>]
      [{#/.Simple {<tag> _}}
       (////\in #Partial)])
    ([#/.Nat]
     [#/.Int]
     [#/.Rev]
     [#/.Frac]
     [#/.Text])

    ... Bits are the exception, since there is only "#1" and
    ... "#0", which means it is possible for bit
    ... pattern-matching to become exhaustive if complementary parts meet.
    {#/.Simple {#/.Bit value}}
    (////\in {#Bit value})

    ... Tuple patterns can be exhaustive if there is exhaustiveness for all of
    ... their sub-patterns.
    {#/.Complex {#/.Tuple membersP+}}
    (case (list.reversed membersP+)
      (^or #.End {#.Item _ #.End})
      (/.except ..invalid_tuple_pattern [])
      
      {#.Item lastP prevsP+}
      (do ////.monad
        [lastC (determine lastP)]
        (monad.mix ////.monad
                   (function (_ leftP rightC)
                     (do ////.monad
                       [leftC (determine leftP)]
                       (case rightC
                         #Exhaustive
                         (in leftC)

                         _
                         (in {#Seq leftC rightC}))))
                   lastC prevsP+)))

    ... Variant patterns can be shown to be exhaustive if all the possible
    ... cases are handled exhaustively.
    {#/.Complex {#/.Variant [lefts right? value]}}
    (do ////.monad
      [value_coverage (determine value)
       .let [idx (if right?
                   (++ lefts)
                   lefts)]]
      (in {#Variant (if right?
                      {#.Some idx}
                      #.None)
           (|> (dictionary.empty n.hash)
               (dictionary.has idx value_coverage))}))))

(def: (xor left right)
  (-> Bit Bit Bit)
  (or (and left (not right))
      (and (not left) right)))

... The coverage checker not only verifies that pattern-matching is
... exhaustive, but also that there are no redundant patterns.
... Redundant patterns will never be executed, since there will
... always be a pattern prior to them that would match the input.
... Because of that, the presence of redundant patterns is assumed to
... be a bug, likely due to programmer carelessness.
(exception: .public (redundant_pattern [so_far Coverage
                                        addition Coverage])
  (exception.report
   ["Coverage so-far" (%coverage so_far)]
   ["Coverage addition" (%coverage addition)]))

(def: (flat_alt coverage)
  (-> Coverage (List Coverage))
  (case coverage
    {#Alt left right}
    (list& left (flat_alt right))

    _
    (list coverage)))

(implementation: equivalence (Equivalence Coverage)
  (def: (= reference sample)
    (case [reference sample]
      [#Exhaustive #Exhaustive]
      #1

      [{#Bit sideR} {#Bit sideS}]
      (bit\= sideR sideS)

      [{#Variant allR casesR} {#Variant allS casesS}]
      (and (n.= (cases allR)
                (cases allS))
           (\ (dictionary.equivalence =) = casesR casesS))
      
      [{#Seq leftR rightR} {#Seq leftS rightS}]
      (and (= leftR leftS)
           (= rightR rightS))

      [{#Alt _} {#Alt _}]
      (let [flatR (flat_alt reference)
            flatS (flat_alt sample)]
        (and (n.= (list.size flatR) (list.size flatS))
             (list.every? (function (_ [coverageR coverageS])
                            (= coverageR coverageS))
                          (list.zipped/2 flatR flatS))))

      _
      #0)))

(open: "coverage/[0]" ..equivalence)

(exception: .public (variants_do_not_match [addition_cases Nat
                                            so_far_cases Nat])
  (exception.report
   ["So-far Cases" (%.nat so_far_cases)]
   ["Addition Cases" (%.nat addition_cases)]))

... After determining the coverage of each individual pattern, it is
... necessary to merge them all to figure out if the entire
... pattern-matching expression is exhaustive and whether it contains
... redundant patterns.
(def: .public (merged addition so_far)
  (-> Coverage Coverage (Try Coverage))
  (case [addition so_far]
    [#Partial #Partial]
    (try\in #Partial)

    ... 2 bit coverages are exhaustive if they complement one another.
    (^multi [{#Bit sideA} {#Bit sideSF}]
            (xor sideA sideSF))
    (try\in #Exhaustive)

    [{#Variant allA casesA} {#Variant allSF casesSF}]
    (let [addition_cases (cases allSF)
          so_far_cases (cases allA)]
      (cond (and (known_cases? addition_cases)
                 (known_cases? so_far_cases)
                 (not (n.= addition_cases so_far_cases)))
            (exception.except ..variants_do_not_match [addition_cases so_far_cases])

            (\ (dictionary.equivalence ..equivalence) = casesSF casesA)
            (exception.except ..redundant_pattern [so_far addition])

            ... else
            (do [! try.monad]
              [casesM (monad.mix !
                                 (function (_ [tagA coverageA] casesSF')
                                   (case (dictionary.value tagA casesSF')
                                     {#.Some coverageSF}
                                     (do !
                                       [coverageM (merged coverageA coverageSF)]
                                       (in (dictionary.has tagA coverageM casesSF')))

                                     #.None
                                     (in (dictionary.has tagA coverageA casesSF'))))
                                 casesSF (dictionary.entries casesA))]
              (in (if (and (or (known_cases? addition_cases)
                               (known_cases? so_far_cases))
                           (n.= (++ (n.max addition_cases so_far_cases))
                                (dictionary.size casesM))
                           (list.every? exhaustive? (dictionary.values casesM)))
                    #Exhaustive
                    {#Variant (case allSF
                                {#.Some _}
                                allSF

                                _
                                allA)
                     casesM})))))

    [{#Seq leftA rightA} {#Seq leftSF rightSF}]
    (case [(coverage/= leftSF leftA) (coverage/= rightSF rightA)]
      ... Same prefix
      [#1 #0]
      (do try.monad
        [rightM (merged rightA rightSF)]
        (if (exhaustive? rightM)
          ... If all that follows is exhaustive, then it can be safely dropped
          ... (since only the "left" part would influence whether the
          ... merged coverage is exhaustive or not).
          (in leftSF)
          (in {#Seq leftSF rightM})))

      ... Same suffix
      [#0 #1]
      (do try.monad
        [leftM (merged leftA leftSF)]
        (in {#Seq leftM rightA}))

      ... The 2 sequences cannot possibly be merged.
      [#0 #0]
      (try\in {#Alt so_far addition})

      ... There is nothing the addition adds to the coverage.
      [#1 #1]
      (exception.except ..redundant_pattern [so_far addition]))

    ... The addition cannot possibly improve the coverage.
    [_ #Exhaustive]
    (exception.except ..redundant_pattern [so_far addition])

    ... The addition completes the coverage.
    [#Exhaustive _]
    (try\in #Exhaustive)
    
    ... The left part will always match, so the addition is redundant.
    (^multi [{#Seq left right} single]
            (coverage/= left single))
    (exception.except ..redundant_pattern [so_far addition])

    ... The right part is not necessary, since it can always match the left.
    (^multi [single {#Seq left right}]
            (coverage/= left single))
    (try\in single)

    ... When merging a new coverage against one based on Alt, it may be
    ... that one of the many coverages in the Alt is complementary to
    ... the new one, so effort must be made to fuse carefully, to match
    ... the right coverages together.
    ... If one of the Alt sub-coverages matches the new one, the cycle
    ... must be repeated, in case the resulting coverage can now match
    ... other ones in the original Alt.
    ... This process must be repeated until no further productive
    ... merges can be done.
    [_ {#Alt leftS rightS}]
    (do [! try.monad]
      [.let [fuse_once (: (-> Coverage (List Coverage)
                              (Try [(Maybe Coverage)
                                    (List Coverage)]))
                          (function (_ coverageA possibilitiesSF)
                            (loop [altsSF possibilitiesSF]
                              (case altsSF
                                #.End
                                (in [#.None (list coverageA)])
                                
                                {#.Item altSF altsSF'}
                                (case (merged coverageA altSF)
                                  {#try.Success altMSF}
                                  (case altMSF
                                    {#Alt _}
                                    (do !
                                      [[success altsSF+] (recur altsSF')]
                                      (in [success {#.Item altSF altsSF+}]))

                                    _
                                    (in [{#.Some altMSF} altsSF']))
                                  
                                  {#try.Failure error}
                                  {#try.Failure error})
                                ))))]
       [successA possibilitiesSF] (fuse_once addition (flat_alt so_far))]
      (loop [successA successA
             possibilitiesSF possibilitiesSF]
        (case successA
          {#.Some coverageA'}
          (do !
            [[successA' possibilitiesSF'] (fuse_once coverageA' possibilitiesSF)]
            (recur successA' possibilitiesSF'))
          
          #.None
          (case (list.reversed possibilitiesSF)
            {#.Item last prevs}
            (in (list\mix (function (_ left right) {#Alt left right})
                          last
                          prevs))

            #.End
            (undefined)))))

    _
    (if (coverage/= so_far addition)
      ... The addition cannot possibly improve the coverage.
      (exception.except ..redundant_pattern [so_far addition])
      ... There are now 2 alternative paths.
      (try\in {#Alt so_far addition}))))