-
Notifications
You must be signed in to change notification settings - Fork 345
/
Builtins.lean
1295 lines (1197 loc) Β· 56.4 KB
/
Builtins.lean
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich, Leonardo de Moura, Gabriel Ebner, Mario Carneiro
-/
prelude
import Lean.Parser
import Lean.PrettyPrinter.Delaborator.Attributes
import Lean.PrettyPrinter.Delaborator.Basic
import Lean.PrettyPrinter.Delaborator.SubExpr
import Lean.PrettyPrinter.Delaborator.TopDownAnalyze
import Lean.Meta.CoeAttr
namespace Lean.PrettyPrinter.Delaborator
open Lean.Meta
open Lean.Parser.Term
open SubExpr
open TSyntax.Compat
/--
If `cond` is true, wraps the syntax produced by `d` in a type ascription.
-/
def withTypeAscription (d : Delab) (cond : Bool := true) : DelabM Term := do
let stx β d
if cond then
let stx β annotateCurPos stx
let typeStx β withType delab
`(($stx : $typeStx))
else
return stx
/--
Wraps the identifier (or identifier with explicit universe levels) with `@` if `pp.analysis.blockImplicit` is set to true.
-/
def maybeAddBlockImplicit (identLike : Syntax) : DelabM Syntax := do
if β getPPOption getPPAnalysisBlockImplicit then `(@$identLike) else pure identLike
@[builtin_delab fvar]
def delabFVar : Delab := do
let Expr.fvar fvarId β getExpr | unreachable!
try
let l β fvarId.getDecl
maybeAddBlockImplicit (mkIdent l.userName)
catch _ =>
-- loose free variable, use internal name
maybeAddBlockImplicit <| mkIdent (fvarId.name.replacePrefix `_uniq `_fvar)
-- loose bound variable, use pseudo syntax
@[builtin_delab bvar]
def delabBVar : Delab := do
let Expr.bvar idx β getExpr | unreachable!
pure $ mkIdent $ Name.mkSimple $ "#" ++ toString idx
@[builtin_delab mvar]
def delabMVar : Delab := do
let Expr.mvar n β getExpr | unreachable!
withTypeAscription (cond := β getPPOption getPPMVarsWithType) do
if β getPPOption getPPMVars then
let mvarDecl β n.getDecl
let n :=
match mvarDecl.userName with
| .anonymous => n.name.replacePrefix `_uniq `m
| n => n
`(?$(mkIdent n))
else
`(?_)
@[builtin_delab sort]
def delabSort : Delab := do
let Expr.sort l β getExpr | unreachable!
match l with
| Level.zero => `(Prop)
| Level.succ .zero => `(Type)
| _ =>
let mvars β getPPOption getPPMVars
match l.dec with
| some l' => `(Type $(Level.quote l' (prec := max_prec) (mvars := mvars)))
| none => `(Sort $(Level.quote l (prec := max_prec) (mvars := mvars)))
/--
Delaborator for `const` expressions.
This is not registered as a delaborator, as `const` is not an expression kind
(see [delab] description and `Lean.PrettyPrinter.Delaborator.getExprKind`).
Rather, it is called through the `app` delaborator.
-/
def delabConst : Delab := do
let Expr.const cβ ls β getExpr | unreachable!
let cβ := if (β getPPOption getPPPrivateNames) then cβ else (privateToUserName? cβ).getD cβ
let mut c β unresolveNameGlobal cβ (fullNames := β getPPOption getPPFullNames)
let stx β if ls.isEmpty || !(β getPPOption getPPUniverses) then
if (β getLCtx).usesUserName c then
-- `c` is also a local declaration
if c == cβ && !(β read).inPattern then
-- `c` is the fully qualified named. So, we append the `_root_` prefix
c := `_root_ ++ c
else
c := cβ
pure <| mkIdent c
else
let mvars β getPPOption getPPMVars
`($(mkIdent c).{$[$(ls.toArray.map (Level.quote Β· (prec := 0) (mvars := mvars)))],*})
let stx β maybeAddBlockImplicit stx
if (β getPPOption getPPTagAppFns) then
annotateTermInfo stx
else
return stx
def withMDataOptions [Inhabited Ξ±] (x : DelabM Ξ±) : DelabM Ξ± := do
match β getExpr with
| Expr.mdata m .. =>
let mut posOpts := (β read).optionsPerPos
let pos β getPos
for (k, v) in m do
if (`pp).isPrefixOf k then
let opts := posOpts.find? pos |>.getD {}
posOpts := posOpts.insert pos (opts.insert k v)
withReader ({ Β· with optionsPerPos := posOpts }) $ withMDataExpr x
| _ => x
partial def withMDatasOptions [Inhabited Ξ±] (x : DelabM Ξ±) : DelabM Ξ± := do
if (β getExpr).isMData then withMDataOptions (withMDatasOptions x) else x
/--
A structure that records details of a function parameter.
-/
structure ParamKind where
/-- Binder name for the parameter. -/
name : Name
/-- Binder info for the parameter. -/
bInfo : BinderInfo
/-- The default value for the parameter, if the parameter has a default value. -/
defVal : Option Expr := none
/-- Whether the parameter is an autoparam (i.e., whether it uses a tactic for the default value). -/
isAutoParam : Bool := false
deriving Inhabited
/--
Returns true if the parameter is an explicit parameter that has neither a default value nor a tactic.
-/
def ParamKind.isRegularExplicit (param : ParamKind) : Bool :=
param.bInfo.isExplicit && !param.isAutoParam && param.defVal.isNone
/--
Given a function `f` supplied with arguments `args`, returns an array whose n-th element
is set to the kind of the n-th argument's associated parameter.
We do not assume the expression `mkAppN f args` is sensical,
and this function captures errors (except for panics) and returns the empty array in that case.
The returned array might be longer than the number of arguments.
It gives parameter kinds for the fully-applied function.
Note: the `defVal` expressions are only guaranteed to be valid for parameters associated to the supplied arguments;
after this, they might refer to temporary fvars.
This function properly handles "overapplied" functions.
For example, while `id` takes one explicit argument, it can take more than one explicit
argument when its arguments are specialized to function types, like in `id id 2`.
-/
def getParamKinds (f : Expr) (args : Array Expr) : MetaM (Array ParamKind) := do
try
let mut result : Array ParamKind := Array.mkEmpty args.size
let mut fnType β inferType f
let mut j := 0
for i in [0:args.size] do
unless fnType.isForall do
fnType β withTransparency .all <| whnf (fnType.instantiateRevRange j i args)
j := i
let .forallE n t b bi := fnType | failure
let defVal := t.getOptParamDefault? |>.map (Β·.instantiateRevRange j i args)
result := result.push { name := n, bInfo := bi, defVal, isAutoParam := t.isAutoParam }
fnType := b
fnType := fnType.instantiateRevRange j args.size args
-- We still want to consider parameters past the ones for the supplied arguments for analysis.
forallTelescopeReducing fnType fun xs _ => do
xs.foldlM (init := result) fun result x => do
let l β x.fvarId!.getDecl
-- Warning: the defVal might refer to fvars that are only valid in this context
pure <| result.push { name := l.userName, bInfo := l.binderInfo, defVal := l.type.getOptParamDefault?, isAutoParam := l.type.isAutoParam }
catch _ => pure #[] -- recall that expr may be nonsensical
def shouldShowMotive (motive : Expr) (opts : Options) : MetaM Bool := do
pure (getPPMotivesAll opts)
<||> (pure (getPPMotivesPi opts) <&&> returnsPi motive)
<||> (pure (getPPMotivesNonConst opts) <&&> isNonConstFun motive)
/--
Takes application syntax and converts it into structure instance notation, if possible.
Assumes that the application is pretty printed in implicit mode.
-/
def unexpandStructureInstance (stx : Syntax) : Delab := whenPPOption getPPStructureInstances do
let env β getEnv
let e β getExpr
let some s β isConstructorApp? e | failure
guard <| isStructure env s.induct
/- If implicit arguments should be shown, and the structure has parameters, we should not
pretty print using { ... }, because we will not be able to see the parameters. -/
let fieldNames := getStructureFields env s.induct
let mut fields := #[]
guard $ fieldNames.size == stx[1].getNumArgs
if hasPPUsingAnonymousConstructorAttribute env s.induct then
return β withTypeAscription (cond := (β withType <| getPPOption getPPStructureInstanceType)) do
`(β¨$[$(stx[1].getArgs)],*β©)
let args := e.getAppArgs
let fieldVals := args.extract s.numParams args.size
for idx in [:fieldNames.size] do
let fieldName := fieldNames[idx]!
if (β getPPOption getPPStructureInstancesFlatten) && (Lean.isSubobjectField? env s.induct fieldName).isSome then
match stx[1][idx] with
| `({ $fields',* $[: $_]?}) =>
-- We have found a subobject field that itself is printed with structure instance notation.
-- Scavange its fields.
fields := fields ++ fields'.getElems
continue
| _ => pure ()
let fieldId := mkIdent fieldName
let fieldPos β nextExtraPos
let fieldId := annotatePos fieldPos fieldId
addFieldInfo fieldPos (s.induct ++ fieldName) fieldName fieldId fieldVals[idx]!
let field β `(structInstField|$fieldId:ident := $(stx[1][idx]))
fields := fields.push field
let tyStx β withType do
if (β getPPOption getPPStructureInstanceType) then delab >>= pure β some else pure none
`({ $fields,* $[: $tyStx]? })
/--
If `e` is an application that is a candidate for using field notation,
returns the parameter index and the field name to use.
Checks that there are enough arguments.
-/
def appFieldNotationCandidate? : DelabM (Option (Nat Γ Name)) := do
let e β getExpr
unless e.isApp do return none
let some (field, idx) β fieldNotationCandidate? e.getAppFn e.getAppArgs (β getPPOption getPPFieldNotationGeneralized)
| return none
unless idx < e.getAppNumArgs do return none
/-
There are some kinds of expressions that cause issues with field notation,
so we prevent using it in these cases.
For example, `2.succ` is not parseable.
-/
let obj := e.getArg! idx
if obj.isRawNatLit || obj.isAppOfArity ``OfNat.ofNat 3 || obj.isAppOfArity ``OfScientific.ofScientific 5 then
return none
return (idx, field)
/--
Consumes projections to parent structures, and runs `d` in the resulting context.
For example, if the current expression is `o.toB.toA`, runs `d` with `o` as the current expression.
If `explicit` is true, then does not consume parent projections for structures with parameters,
since these are implicit arguments.
-/
private partial def withoutParentProjections (explicit : Bool) (d : DelabM Ξ±) : DelabM Ξ± := do
if β try isParentProj explicit (β getExpr) catch _ => pure false then
withAppArg <| withoutParentProjections explicit d
else
d
-- TODO(kmill): make sure that we only strip projections so long as it doesn't change how it elaborates.
-- This affects `withoutParentProjections` as well.
/-- Strips parent projections from `s`. Assumes that the current SubExpr is the same as the one used when delaborating `s`. -/
private partial def stripParentProjections (s : Term) : DelabM Term :=
match s with
| `($x.$f:ident) => do
if let some field β try parentProj? false (β getExpr) catch _ => pure none then
if f.getId == field then
withAppArg <| stripParentProjections x
else
return s
else
return s
| _ => return s
/--
In explicit mode, decides whether or not the applied function needs `@`,
where `numArgs` is the number of arguments actually supplied to `f`.
-/
def needsExplicit (f : Expr) (numArgs : Nat) (paramKinds : Array ParamKind) : Bool :=
if paramKinds.size == 0 && 0 < numArgs && f matches .const _ [] then
-- Error calculating ParamKinds,
-- but we presume that the universe list has been intentionally erased, for example by LCNF.
-- The arguments in this case are *only* the explicit arguments, so we don't want to prefix with `@`.
false
else
-- Error calculating ParamKinds, so return `true` to be safe
paramKinds.size < numArgs
-- One of the supplied parameters isn't explicit
|| paramKinds[:numArgs].any (fun param => !param.bInfo.isExplicit)
-- The next parameter is implicit or inst implicit
|| (numArgs < paramKinds.size && paramKinds[numArgs]!.bInfo matches .implicit | .instImplicit)
-- One of the parameters after the supplied parameters is explicit but not regular explicit.
|| paramKinds[numArgs:].any (fun param => param.bInfo.isExplicit && !param.isRegularExplicit)
/--
Delaborates a function application in explicit mode.
* If `insertExplicit` is true, then ensures the head syntax is wrapped with `@`.
* If `fieldNotation` is true, then allows the application to be pretty printed using field notation.
Field notation will not be used when `insertExplicit` is true.
-/
def delabAppExplicitCore (fieldNotation : Bool) (numArgs : Nat) (delabHead : (insertExplicit : Bool) β Delab) (paramKinds : Array ParamKind) : Delab := do
let insertExplicit := needsExplicit ((β getExpr).getBoundedAppFn numArgs) numArgs paramKinds
let fieldNotation β pure (fieldNotation && !insertExplicit) <&&> getPPOption getPPFieldNotation
<&&> not <$> getPPOption getPPAnalysisNoDot
<&&> withBoundedAppFn numArgs do pure (β getExpr).consumeMData.isConst <&&> not <$> withMDatasOptions (getPPOption getPPAnalysisBlockImplicit <|> getPPOption getPPUniverses)
let field? β if fieldNotation then appFieldNotationCandidate? else pure none
let (fnStx, _, argStxs) β withBoundedAppFnArgs numArgs
(do return (β delabHead insertExplicit, paramKinds.toList, Array.mkEmpty numArgs))
(fun β¨fnStx, paramKinds, argStxsβ© => do
let isInstImplicit := paramKinds.head? |>.map (Β·.bInfo == .instImplicit) |>.getD false
let argStx β if some argStxs.size = field?.map Prod.fst then
-- With field notation, we can erase parent projections for the object
withoutParentProjections (explicit := true) delab
else if β getPPOption getPPAnalysisHole then `(_)
else if isInstImplicit == true then
withTypeAscription (cond := β getPPOption getPPInstanceTypes) do
if β getPPOption getPPInstances then delab else `(_)
else delab
pure (fnStx, paramKinds.tailD [], argStxs.push argStx))
if let some (idx, field) := field? then
-- Delaborate using field notation
let obj := argStxs[idx]!
let mut head : Term β `($obj.$(mkIdent field))
if idx == 0 then
-- If it's the first argument, then we can tag `obj.field` with the first app.
head β withBoundedAppFn (numArgs - 1) <| annotateTermInfo head
return Syntax.mkApp head (argStxs.eraseIdx idx)
else
return Syntax.mkApp fnStx argStxs
/-- Records how a particular argument to a function is delaborated, in non-explicit mode. -/
inductive AppImplicitArg
/-- An argument to skip, like an implicit argument. -/
| skip
/-- A regular argument. -/
| regular (s : Term)
/-- It's a named argument. Named arguments inhibit applying unexpanders. -/
| named (s : TSyntax ``Parser.Term.namedArgument)
deriving Inhabited
/-- Whether unexpanding is allowed with this argument. -/
def AppImplicitArg.canUnexpand : AppImplicitArg β Bool
| .regular .. | .skip => true
| .named .. => false
/-- If the argument has associated syntax, returns it. -/
def AppImplicitArg.syntax? : AppImplicitArg β Option Syntax
| .skip => none
| .regular s => s
| .named s => s
/--
Delaborates a function application in the standard mode, where implicit arguments are generally not
included, unless `pp.analysis.namedArg` is set at that argument.
This delaborator is where `app_unexpander`s and the structure instance unexpander are applied, if `unexpand` is true.
When `unexpand` is true, also considers opportunities for field notation, which takes priority over other unexpanders.
Assumes `numArgs β€ paramKinds.size`.
-/
def delabAppImplicitCore (unexpand : Bool) (numArgs : Nat) (delabHead : Delab) (paramKinds : Array ParamKind) : Delab := do
let unexpand β pure unexpand
<&&> withBoundedAppFn numArgs do pure (β getExpr).consumeMData.isConst <&&> not <$> withMDatasOptions (getPPOption getPPUniverses)
let field? β
if β pure unexpand <&&> getPPOption getPPFieldNotation <&&> not <$> getPPOption getPPAnalysisNoDot then
appFieldNotationCandidate?
else
pure none
let (fnStx, args) β
withBoundedAppFnArgs numArgs
(do return ((β delabHead), Array.mkEmpty numArgs))
(fun (fnStx, args) => do
let idx := args.size
let arg β mkArg (numArgs - idx - 1) paramKinds[idx]!
return (fnStx, args.push arg))
-- App unexpanders
if β pure unexpand <&&> getPPOption getPPNotation then
-- Try using an app unexpander for a prefix of the arguments.
if let some stx β (some <$> tryAppUnexpanders fnStx args) <|> pure none then
return stx
let stx := Syntax.mkApp fnStx (args.filterMap (Β·.syntax?))
-- Structure instance notation
if β pure (unexpand && args.all (Β·.canUnexpand)) <&&> getPPOption getPPStructureInstances then
-- Try using the structure instance unexpander.
if let some stx β (some <$> unexpandStructureInstance stx) <|> pure none then
return stx
-- Field notation
if let some (fieldIdx, field) := field? then
if fieldIdx < args.size then
let obj? : Option Term β do
let arg := args[fieldIdx]!
if let .regular s := arg then
withNaryArg fieldIdx <| some <$> stripParentProjections s
else
pure none
if let some obj := obj? then
let isFirst := args[0:fieldIdx].all (Β· matches .skip)
-- Clear the `obj` argument from `args`.
let args' := args.set! fieldIdx .skip
let mut head : Term β `($obj.$(mkIdent field))
if isFirst then
-- If the object is the first argument (after some implicit arguments),
-- we can annotate `obj.field` with the prefix of the application
-- that includes all the implicit arguments immediately before and after `obj`.
let objArity := args'.findIdx? (fun a => !(a matches .skip)) |>.getD args'.size
head β withBoundedAppFn (numArgs - objArity) <| annotateTermInfo <| head
return Syntax.mkApp head (args'.filterMap (Β·.syntax?))
-- Normal application
return stx
where
mkNamedArg (name : Name) : DelabM AppImplicitArg :=
return .named <| β `(Parser.Term.namedArgument| ($(mkIdent name) := $(β delab)))
/--
Delaborates the current argument.
The argument `remainingArgs` is the number of arguments in the application after this one.
-/
mkArg (remainingArgs : Nat) (param : ParamKind) : DelabM AppImplicitArg := do
let arg β getExpr
if β getPPOption getPPAnalysisSkip then return .skip
else if β getPPOption getPPAnalysisHole then return .regular (β `(_))
else if β getPPOption getPPAnalysisNamedArg then
mkNamedArg param.name
else if param.defVal.isSome && remainingArgs == 0 && param.defVal.get! == arg then
-- Assumption: `useAppExplicit` has already detected whether it is ok to omit this argument
return .skip
else if param.bInfo.isExplicit then
return .regular (β delab)
else if β pure (param.name == `motive) <&&> shouldShowMotive arg (β getOptions) then
mkNamedArg param.name
else
return .skip
/--
Runs the given unexpanders, returning the resulting syntax if any are applicable, and otherwise fails.
-/
tryUnexpand (fs : List Unexpander) (stx : Syntax) : DelabM Syntax := do
let ref β getRef
fs.firstM fun f =>
match f stx |>.run ref |>.run () with
| EStateM.Result.ok stx _ => return stx
| _ => failure
/--
If the expression is a candidate for app unexpanders,
try applying an app unexpander using some prefix of the arguments, longest prefix first.
This function makes sure that the unexpanded syntax is annotated and given TermInfo so that it is hoverable in the InfoView.
-/
tryAppUnexpanders (fnStx : Term) (args : Array AppImplicitArg) : Delab := do
let .const c _ := (β getExpr).getAppFn.consumeMData | unreachable!
let fs := appUnexpanderAttribute.getValues (β getEnv) c
if fs.isEmpty then failure
let rec go (i : Nat) (implicitArgs : Nat) (argStxs : Array Syntax) : DelabM Term := do
match i with
| 0 =>
let stx β tryUnexpand fs fnStx
return Syntax.mkApp (β annotateTermInfo stx) (args.filterMap (Β·.syntax?))
| i' + 1 =>
if args[i']!.syntax?.isSome then
(do let stx β tryUnexpand fs <| Syntax.mkApp fnStx argStxs
let argStxs' := args.extract i args.size |>.filterMap (Β·.syntax?)
return Syntax.mkApp (β annotateTermInfo stx) argStxs')
<|> withBoundedAppFn (implicitArgs + 1) (go i' 0 argStxs.pop)
else
go i' (implicitArgs + 1) argStxs
let maxUnexpand := args.findIdx? (!Β·.canUnexpand) |>.getD args.size
withBoundedAppFn (args.size - maxUnexpand) <|
go maxUnexpand 0 (args.extract 0 maxUnexpand |>.filterMap (Β·.syntax?))
/--
Returns true if an application should use explicit mode when delaborating.
Explicit mode turns off unexpanders
-/
def useAppExplicit (numArgs : Nat) (paramKinds : Array ParamKind) : DelabM Bool := do
-- If `pp.explicit` is set, then use explicit mode.
-- (Note that explicit mode can decide to omit `@` if the application has no implicit arguments.)
if β getPPOption getPPExplicit then return true
if β withBoundedAppFn numArgs <| withMDatasOptions <| getPPOption getPPAnalysisBlockImplicit then
return true
-- If there was an error collecting ParamKinds, fall back to explicit mode.
if paramKinds.size < numArgs then return true
if numArgs < paramKinds.size then
let nextParam := paramKinds[numArgs]!
-- If the next parameter is implicit or inst implicit, fall back to explicit mode.
-- This is necessary for `@Eq` for example.
if nextParam.bInfo matches .implicit | .instImplicit then return true
-- If any of the next parameters is explicit but has an optional value or is an autoparam, fall back to explicit mode.
-- This is necessary since these are eagerly processed when elaborating.
if paramKinds[numArgs:].any fun param => param.bInfo.isExplicit && !param.isRegularExplicit then return true
return false
/--
Delaborates applications. Removes up to `maxArgs` arguments to form the "head" of the application.
* `delabHead` is a delaborator to use for the head of the expression.
It is passed whether the result needs to have `@` inserted.
* If `unexpand` is true, then allow unexpanders and field notation.
This should likely be set to `false` except in the main `delabApp` delaborator.
Propagates `pp.tagAppFns` into the head for `delabHead`.
-/
def delabAppCore (maxArgs : Nat) (delabHead : (insertExplicit : Bool) β Delab) (unexpand : Bool) : Delab := do
let tagAppFn β getPPOption getPPTagAppFns
let delabHead' (insertExplicit : Bool) : Delab := withOptionAtCurrPos `pp.tagAppFns tagAppFn (delabHead insertExplicit)
let e β getExpr
let fn := e.getBoundedAppFn maxArgs
let args := e.getBoundedAppArgs maxArgs
let paramKinds β getParamKinds fn args
if (β useAppExplicit args.size paramKinds) then
-- Don't use field notation when `pp.tagAppFns` is true since that obscures the head application.
delabAppExplicitCore (fieldNotation := unexpand && !tagAppFn) args.size delabHead' paramKinds
else
delabAppImplicitCore (unexpand := unexpand) args.size (delabHead' false) paramKinds
/--
Default delaborator for applications.
-/
@[builtin_delab app]
def delabApp : Delab := do
let delabAppFn (insertExplicit : Bool) : Delab := do
let stx β if (β getExpr).consumeMData.isConst then withMDatasOptions delabConst else delab
if insertExplicit && !stx.raw.isOfKind ``Lean.Parser.Term.explicit then `(@$stx) else pure stx
delabAppCore (β getExpr).getAppNumArgs delabAppFn (unexpand := true)
/--
The `withOverApp` combinator allows delaborators to handle "over-application" by using the core
application delaborator to handle additional arguments.
For example, suppose `f : {A : Type} β Foo A β A` and we want to implement a delaborator for
applications `f x` to pretty print as `F[x]`. Because `A` is a type variable we might encounter
a term of the form `@f (A β B) x y`, which has an additional argument `y`.
With this combinator one can use an arity-2 delaborator to pretty print this as `F[x] y`.
* `arity`: the expected number of arguments to `f`.
The combinator will fail if fewer than this number of arguments are passed,
and if more than this number of arguments are passed the arguments are handled using
the standard application delaborator.
* `x`: delaborates the head application of the expected arity (`f x` in the example).
The value of `pp.tagAppFns` for the whole application is propagated to the expression that `x` sees.
In the event of overapplication, the delaborator `x` is wrapped in
`Lean.PrettyPrinter.Delaborator.withAnnotateTermInfo` to register `TermInfo` for the resulting term.
The effect of this is that the term is hoverable in the Infoview.
If the application would require inserting `@` around the result of `x`, the delaborator fails
since we cannot be sure that this insertion will be well-formed.
-/
def withOverApp (arity : Nat) (x : Delab) : Delab := do
let n := (β getExpr).getAppNumArgs
guard <| n β₯ arity
if n == arity then
x
else
let delabHead (insertExplicit : Bool) : Delab := do
guard <| !insertExplicit
withAnnotateTermInfo x
delabAppCore (n - arity) delabHead (unexpand := false)
/-- State for `delabAppMatch` and helpers. -/
structure AppMatchState where
info : MatcherInfo
/-- The `matcherTy` instantiated with universe levels and the matcher parameters, with a position at the type of
this application prefix. -/
matcherTy : SubExpr
/-- The motive, with the pi type version delaborated and the original expression version.
Once `AppMatchState` is complete, this is not `none`. -/
motive : Option (Term Γ Expr) := none
/-- Whether `pp.analysis.namedArg` was set for the motive argument. -/
motiveNamed : Bool := false
/-- The delaborated discriminants, without `h :` annotations. -/
discrs : Array Term := #[]
/-- The collection of names used for the `h :` discriminant annotations, in order.
Uniquified names are constructed after the first phase. -/
hNames? : Array (Option Name) := #[]
/-- Lambda subexpressions for each alternate. -/
alts : Array SubExpr := #[]
/-- For each match alternative, the names to use for the pattern variables.
Each ends with `hNames?.filterMap id` exactly. -/
varNames : Array (Array Name) := #[]
/-- The delaborated right-hand sides for each match alternative. -/
rhss : Array Term := #[]
/--
Skips `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names.
The `hNames` array is used for the last params.
Helper for `delabAppMatch`.
-/
private partial def skippingBinders {Ξ±} (numParams : Nat) (hNames : Array Name) (x : Array Name β DelabM Ξ±) : DelabM Ξ± := do
loop 0 #[]
where
loop (i : Nat) (varNames : Array Name) : DelabM Ξ± := do
let rec visitLambda : DelabM Ξ± := do
let varName := (β getExpr).bindingName!.eraseMacroScopes
if numParams - hNames.size β€ i then
-- It is an "h annotation", so use the one we have already chosen.
let varName := hNames[i + hNames.size - numParams]!
withBindingBody varName do
loop (i + 1) (varNames.push varName)
else if varNames.contains varName then
-- Pattern variables must not shadow each other, so ensure a unique name
let varName := (β getLCtx).getUnusedName varName
withBindingBody varName do
loop (i + 1) (varNames.push varName)
else
withBindingBodyUnusedName fun id => do
loop (i + 1) (varNames.push id.getId)
if i < numParams then
let e β getExpr
if e.isLambda then
visitLambda
else
-- Eta expand `e`
let e β forallTelescopeReducing (β inferType e) fun xs _ => do
if xs.size == 1 && (β inferType xs[0]!).isConstOf ``Unit then
-- `e` might be a thunk create by the dependent pattern matching compiler, and `xs[0]` may not even be a pattern variable.
-- If it is a pattern variable, it doesn't look too bad to use `()` instead of the pattern variable.
-- If it becomes a problem in the future, we should modify the dependent pattern matching compiler, and make sure
-- it adds an annotation to distinguish these two cases.
mkLambdaFVars xs (mkApp e (mkConst ``Unit.unit))
else
mkLambdaFVars xs (mkAppN e xs)
withTheReader SubExpr (fun ctx => { ctx with expr := e }) visitLambda
else x varNames
/--
Delaborates applications of "matchers" such as
```
List.map.match_1 : {Ξ± : Type _} β
(motive : List Ξ± β Sort _) β
(x : List Ξ±) β (Unit β motive List.nil) β ((a : Ξ±) β (as : List Ξ±) β motive (a :: as)) β motive x
```
-/
@[builtin_delab app]
partial def delabAppMatch : Delab := whenPPOption getPPNotation <| whenPPOption getPPMatch do
-- Check that this is a matcher, and then set up overapplication.
let Expr.const c us := (β getExpr).getAppFn | failure
let some info β getMatcherInfo? c | failure
withOverApp info.arity do
-- First pass visiting the match application. Incrementally fills `AppMatchState`,
-- collecting information needed to delaborate the patterns and RHSs.
-- No need to visit the parameters themselves.
let st : AppMatchState β withBoundedAppFnArgs (1 + info.numDiscrs + info.numAlts)
(do
let params := (β getExpr).getAppArgs
let matcherTy : SubExpr :=
{ expr := β instantiateForall (β instantiateTypeLevelParams (β getConstInfo c) us) params
pos := (β getPos).pushType }
guard <| β isDefEq matcherTy.expr (β inferType (β getExpr))
return { info, matcherTy })
(fun st => do
if st.motive.isNone then
-- A motive for match notation is a type, so need to delaborate the lambda motive as a pi type.
let lamMotive β getExpr
let piMotive β lambdaTelescope lamMotive fun xs body => mkForallFVars xs body
-- TODO: pp.analyze has not analyzed `piMotive`, only `lamMotive`
-- Thus the binder types won't have any annotations.
-- Though, by using the same position we can use the body annotations
let piStx β withTheReader SubExpr (fun cfg => { cfg with expr := piMotive }) delab
let named β getPPOption getPPAnalysisNamedArg
return { st with motive := (piStx, lamMotive), motiveNamed := named }
else if st.discrs.size < st.info.numDiscrs then
return { st with discrs := st.discrs.push (β delab) }
else if st.alts.size < st.info.numAlts then
return { st with alts := st.alts.push (β readThe SubExpr) }
else
panic! "impossible, number of arguments does not match arity")
-- Second pass, create names for the h parameters, come up with pattern variable names,
-- and delaborate the RHSs.
-- We need to create dummy variables for the `h :` annotation variables first because they
-- come *last* in each alternative.
let st β withDummyBinders (st.info.discrInfos.map (Β·.hName?)) (β getExpr) fun hNames? => do
let hNames := hNames?.filterMap id
let mut st := {st with hNames? := hNames?}
for i in [0:st.alts.size] do
st β withTheReader SubExpr (fun _ => st.alts[i]!) do
-- We save the variables names here to be able to implement safe shadowing.
-- The pattern delaboration must use the names saved here.
skippingBinders st.info.altNumParams[i]! hNames fun varNames => do
let rhs β delab
return { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames }
return st
if st.rhss.isEmpty then
`(nomatch $(st.discrs),*)
else
-- Third pass, delaborate patterns.
-- Extracts arguments of motive applications from the matcher type.
-- For the example in the docstring, yields `#[#[([])], #[(a::as)]]`.
let pats β withReader (fun ctx => { ctx with inPattern := true, subExpr := st.matcherTy }) do
-- Need to reduce since there can be `let`s that are lifted into the matcher type
forallTelescopeReducing (β getExpr) fun afterParams _ => do
-- Skip motive and discriminators
let alts := Array.ofSubarray afterParams[1 + st.discrs.size:]
-- Visit minor premises
alts.mapIdxM fun idx alt => do
let altTy β inferType alt
withTheReader SubExpr (fun ctx =>
{ ctx with expr := altTy, pos := ctx.pos.pushNthBindingDomain (1 + st.discrs.size + idx) }) do
usingNames st.varNames[idx]! <|
withAppFnArgs (pure #[]) fun pats => return pats.push (β delab)
-- Finally, assemble
let discrs β (st.hNames?.zip st.discrs).mapM fun (hName?, discr) =>
match hName? with
| none => `(matchDiscr| $discr:term)
| some hName => `(matchDiscr| $(mkIdent hName) : $discr)
let (piStx, lamMotive) := st.motive.get!
let opts β getOptions
-- TODO: disable the match if other implicits are needed?
if β pure st.motiveNamed <||> shouldShowMotive lamMotive opts then
`(match (motive := $piStx) $[$discrs:matchDiscr],* with $[| $pats,* => $st.rhss]*)
else
`(match $[$discrs:matchDiscr],* with $[| $pats,* => $st.rhss]*)
where
/-- Adds hNames to the local context to reserve their names and runs `m` in that context. -/
withDummyBinders {Ξ± : Type} (hNames? : Array (Option Name)) (body : Expr)
(m : Array (Option Name) β DelabM Ξ±) (acc : Array (Option Name) := #[]) : DelabM Ξ± := do
let i := acc.size
if i < hNames?.size then
if let some name := hNames?[i]! then
let n' β getUnusedName name body
withLocalDecl n' .default (.sort levelZero) (kind := .implDetail) fun _ =>
withDummyBinders hNames? body m (acc.push n')
else
withDummyBinders hNames? body m (acc.push none)
else
m acc
usingNames {Ξ±} (varNames : Array Name) (x : DelabM Ξ±) (i : Nat := 0) : DelabM Ξ± :=
if i < varNames.size then
withBindingBody varNames[i]! <| usingNames varNames x (i+1)
else
x
/--
Delaborates applications of the form `letFun v (fun x => b)` as `let_fun x := v; b`.
-/
@[builtin_delab app.letFun]
def delabLetFun : Delab := whenPPOption getPPNotation <| withOverApp 4 do
let e β getExpr
guard <| e.getAppNumArgs == 4
let Expr.lam n _ b _ := e.appArg! | failure
let n β getUnusedName n b
let stxV β withAppFn <| withAppArg delab
let (stxN, stxB) β withAppArg <| withBindingBody' n (mkAnnotatedIdent n) fun stxN => return (stxN, β delab)
if β getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then
let stxT β SubExpr.withNaryArg 0 delab
`(let_fun $stxN : $stxT := $stxV; $stxB)
else
`(let_fun $stxN := $stxV; $stxB)
@[builtin_delab mdata]
def delabMData : Delab := do
if let some _ := inaccessible? (β getExpr) then
let s β withMDataExpr delab
if (β read).inPattern then
`(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns
else
return s
else if let some _ := isLHSGoal? (β getExpr) then
withMDataExpr <| withAppFn <| withAppArg <| delab
else
withMDataOptions delab
/--
Check for a `Syntax.ident` of the given name anywhere in the tree.
This is usually a bad idea since it does not check for shadowing bindings,
but in the delaborator we assume that bindings are never shadowed.
-/
partial def hasIdent (id : Name) : Syntax β Bool
| Syntax.ident _ _ id' _ => id == id'
| Syntax.node _ _ args => args.any (hasIdent id)
| _ => false
/--
Return `true` iff current binder should be merged with the nested
binder, if any, into a single binder group:
* both binders must have same binder info and domain
* they cannot be inst-implicit (`[a b : A]` is not valid syntax)
* `pp.binderTypes` must be the same value for both terms
* prefer `fun a b` over `fun (a b)`
-/
private def shouldGroupWithNext : DelabM Bool := do
let e β getExpr
let ppEType β getPPOption (getPPBinderTypes e)
let go (e' : Expr) := do
let ppE'Type β withBindingBody `_ $ getPPOption (getPPBinderTypes e)
pure $ e.binderInfo == e'.binderInfo &&
e.bindingDomain! == e'.bindingDomain! &&
e'.binderInfo != BinderInfo.instImplicit &&
ppEType == ppE'Type &&
(e'.binderInfo != BinderInfo.default || ppE'Type)
match e with
| Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e'
| Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e'
| _ => pure false
where
getPPBinderTypes (e : Expr) :=
if e.isForall then getPPPiBinderTypes else getPPFunBinderTypes
private partial def delabBinders (delabGroup : Array Syntax β Syntax β Delab) : optParam (Array Syntax) #[] β Delab
-- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished
-- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping
-- inside-out, on the Syntax level, because it depends on comparing the Expr binder types.
| curNames => do
if β shouldGroupWithNext then
-- group with nested binder => recurse immediately
withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN)
else
-- don't group => delab body and prepend current binder group
let (stx, stxN) β withBindingBodyUnusedName fun stxN => return (β delab, stxN)
delabGroup (curNames.push stxN) stx
@[builtin_delab lam]
def delabLam : Delab :=
delabBinders fun curNames stxBody => do
let e β getExpr
let stxT β withBindingDomain delab
let ppTypes β getPPOption getPPFunBinderTypes
let usedDownstream := curNames.any (fun n => hasIdent n.getId stxBody)
-- leave lambda implicit if possible
-- TODO: for now we just always block implicit lambdas when delaborating. We can revisit.
-- Note: the current issue is that it requires state, i.e. if *any* previous binder was implicit,
-- it doesn't seem like we can leave a subsequent binder implicit.
let blockImplicitLambda := true
/-
let blockImplicitLambda := expl ||
e.binderInfo == BinderInfo.default ||
-- Note: the following restriction fixes many issues with roundtripping,
-- but this condition may still not be perfectly in sync with the elaborator.
e.binderInfo == BinderInfo.instImplicit ||
Elab.Term.blockImplicitLambda stxBody ||
usedDownstream
-/
if !blockImplicitLambda then
pure stxBody
else
let defaultCase (_ : Unit) : Delab := do
if ppTypes then
-- "default" binder group is the only one that expects binder names
-- as a term, i.e. a single `Syntax.ident` or an application thereof
let stxCurNames β
if curNames.size > 1 then
`($(curNames.get! 0) $(curNames.eraseIdx 0)*)
else
pure $ curNames.get! 0;
`(funBinder| ($stxCurNames : $stxT))
else
pure curNames.back -- here `curNames.size == 1`
let group β match e.binderInfo, ppTypes with
| BinderInfo.default, _ => defaultCase ()
| BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT})
| BinderInfo.implicit, false => `(funBinder| {$curNames*})
| BinderInfo.strictImplicit, true => `(funBinder| β¦$curNames* : $stxTβ¦)
| BinderInfo.strictImplicit, false => `(funBinder| β¦$curNames*β¦)
| BinderInfo.instImplicit, _ =>
if usedDownstream then `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1`
else `(funBinder| [$stxT])
let (binders, stxBody) :=
match stxBody with
| `(fun $binderGroups* => $stxBody) => (#[group] ++ binderGroups, stxBody)
| _ => (#[group], stxBody)
if β getPPOption getPPUnicodeFun then
`(fun $binders* β¦ $stxBody)
else
`(fun $binders* => $stxBody)
/--
Similar to `delabBinders`, but tracking whether `forallE` is dependent or not.
See issue #1571
-/
private partial def delabForallBinders (delabGroup : Array Syntax β Bool β Syntax β Delab) (curNames : Array Syntax := #[]) (curDep := false) : Delab := do
let dep := !(β getExpr).isArrow
if !curNames.isEmpty && dep != curDep then
-- don't group
delabGroup curNames curDep (β delab)
else
let curDep := dep
if β shouldGroupWithNext then
-- group with nested binder => recurse immediately
withBindingBodyUnusedName fun stxN => delabForallBinders delabGroup (curNames.push stxN) curDep
else
-- don't group => delab body and prepend current binder group
let (stx, stxN) β withBindingBodyUnusedName fun stxN => return (β delab, stxN)
delabGroup (curNames.push stxN) curDep stx
@[builtin_delab forallE]
def delabForall : Delab := do
delabForallBinders fun curNames dependent stxBody => do
let e β getExpr
let prop β try isProp e catch _ => pure false
let stxT β withBindingDomain delab
let group β match e.binderInfo with
| BinderInfo.implicit => `(bracketedBinderF|{$curNames* : $stxT})
| BinderInfo.strictImplicit => `(bracketedBinderF|β¦$curNames* : $stxTβ¦)
-- here `curNames.size == 1`
| BinderInfo.instImplicit => `(bracketedBinderF|[$curNames.back : $stxT])
| _ =>
-- NOTE: non-dependent arrows are available only for the default binder info
if dependent then
if prop && !(β getPPOption getPPPiBinderTypes) then
return β `(β $curNames:ident*, $stxBody)
else
`(bracketedBinderF|($curNames* : $stxT))
else
return β curNames.foldrM (fun _ stxBody => `($stxT β $stxBody)) stxBody
if prop then
match stxBody with
| `(β $groups*, $stxBody) => `(β $group $groups*, $stxBody)
| _ => `(β $group, $stxBody)
else
`($group:bracketedBinder β $stxBody)
@[builtin_delab letE]
def delabLetE : Delab := do
let Expr.letE n t v b _ β getExpr | unreachable!
let n β getUnusedName n b
let stxV β descend v 1 delab
let (stxN, stxB) β withLetDecl n t v fun fvar => do
let b := b.instantiate1 fvar
return (β mkAnnotatedIdent n fvar, β descend b 2 delab)
if β getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then
let stxT β descend t 0 delab
`(let $stxN : $stxT := $stxV; $stxB)
else `(let $stxN := $stxV; $stxB)
@[builtin_delab app.Char.ofNat]
def delabChar : Delab := do
let e β getExpr
guard <| e.getAppNumArgs == 1
let .lit (.natVal n) := e.appArg! | failure
return quote (Char.ofNat n)
@[builtin_delab lit]
def delabLit : Delab := do
let Expr.lit l β getExpr | unreachable!
match l with
| Literal.natVal n =>
if β getPPOption getPPNatLit then
`(nat_lit $(quote n))
else
return quote n
| Literal.strVal s => return quote s
/--
Core function that delaborates a natural number (an `OfNat.ofNat` literal).
-/
def delabOfNatCore (showType : Bool := false) : Delab := do
let .app (.app (.app (.const ``OfNat.ofNat ..) _) (.lit (.natVal n))) _ β getExpr | failure
let stx β annotateTermInfo <| quote n
if showType then
let ty β withNaryArg 0 delab
`(($stx : $ty))
else
return stx
/--
Core function that delaborates a negative integer literal (a `Neg.neg` applied to `OfNat.ofNat`).
-/
def delabNegIntCore (showType : Bool := false) : Delab := do
guard <| (β getExpr).isAppOfArity ``Neg.neg 3
let n β withAppArg delabOfNatCore
let stx β annotateTermInfo (β `(- $n))
if showType then
let ty β withNaryArg 0 delab
`(($stx : $ty))
else
return stx
/--
Core function that delaborates a rational literal that is the division of an integer literal
by a natural number literal.
The division must be homogeneous for it to count as a rational literal.
-/
def delabDivRatCore (showType : Bool := false) : Delab := do
let e β getExpr
guard <| e.isAppOfArity ``HDiv.hDiv 6
guard <| e.getArg! 0 == e.getArg! 1
guard <| e.getArg! 0 == e.getArg! 2
let p β withAppFn <| withAppArg <| (delabOfNatCore <|> delabNegIntCore)
let q β withAppArg <| delabOfNatCore
let stx β annotateTermInfo (β `($p / $q))
if showType then
let ty β withNaryArg 0 delab
`(($stx : $ty))
else
return stx
/--