Repository navigation
Expand file tree
/
Copy pathElaborator.lean
More file actions
1287 lines (1223 loc) · 69.7 KB
/
Copy pathElaborator.lean
File metadata and controls
1287 lines (1223 loc) · 69.7 KB
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
module
public import ConstructiveCryptography.DSL.Equations
public import RandomSystems.Typed.DSL.Syntax
public import RandomSystems.Typed.DSL.Converters
public import RandomSystems.Typed.DSL.Tactics
public import RandomSystems.Typed.Source
public import RandomSystems.Typed.Context
public import RandomSystems.Typed.Filter
public import RandomSystems.Typed.InterfaceCoherence
public import ConstructiveCryptography.Notation
/-!
# The component compiler
Interfaces, systems, converters and filters are compiled to finite systems at every query
budget. Every sampling statement becomes a call to a source of fresh samples from its law, so a
component is a deterministic program with sources: a converter is its program followed by the
context attaching its sources, and a system is its program attached to its sources; a system
that samples nothing is the deterministic system of its program. Initialization runs in the
first invocation. Named `outside` components `a : A`, `b : B`, `c : C` give the ordered tensor
`A q₁ ⊗ (B q₂ ⊗ C q₃)` at the budget tuple `(q₁, q₂, q₃)`; one component keeps a scalar budget.
A converter gets its inferred per-call bound `C.bound` and an inside allowance
of `C.bound` times its outside interface's bound, plus the exact arrow `C.exact` when its number of
inside calls is a function of the input; a filter is the arrow from the restricted budget.
System definitions take their budget from their outermost component. Leading docstrings are
attached to the public declaration and its generated per-port and exact forms.
The compiler is a front end
on the category of interfaces: systems are `TypedSystem`s, and converters, built from
`TypedConverter.ofProgram` and its variants, are declared as arrows `A ⟶ B` of
`Interface.category`, so that components assemble with `≫` and `⊗ₘ`.
A declaration that elaborates without errors also gets its per-procedure equations
(`elabComponentEquations`), and its newly generated wrappers are registered in
`component_definitions` (`registerComponentDefinitions`), so that `inline` expands them.
-/
@[expose] public meta section
namespace SystemAlgebra.DSL
open Lean Elab Command Parser Term
open CategoryTheory MonoidalCategory
/-- Bound names tracked only during elaboration; no runtime environment is generated. -/
def targetNames (t : Syntax) : Array Ident :=
if t[0].isIdent then #[⟨t[0]⟩] else t[0][1].getSepArgs.map (⟨·⟩)
partial def tupleTerm (xs : Array (TSyntax `term)) : CommandElabM (TSyntax `term) :=
if xs.isEmpty then `(())
else if xs.size = 1 then pure xs[0]!
else do
let tail ← tupleTerm (xs.extract 1 xs.size)
`(($(xs[0]!), $tail))
def statements (b : Syntax) : Array Syntax := b[0].getArgs
partial def identifiers (s : Syntax) : Array Name :=
if s.isIdent then #[s.getId] else s.getArgs.flatMap identifiers
def checkPure (s : Syntax) (calls : Array (Name × TSyntax `term)) : CommandElabM Unit := do
if (identifiers s).any (fun n => calls.any (·.1 == n)) then
throwErrorAt s "Inside calls must occupy an entire assignment right-hand side."
/-- Report a wrong reply against the declared alphabet, before pairing it with
private bindings in the generated function. -/
partial def annotateReturns (s : Syntax) (ty : TSyntax `term) : CommandElabM Syntax := do
if s.getKind == ``returnStmt then
let rhs ← `(($(⟨s[1]⟩):term : $ty))
return s.setArg 1 rhs.raw
match s with
| .node info kind args => return .node info kind (← args.mapM (annotateReturns · ty))
| _ => return s
partial def returns (b : Syntax) : Bool :=
match (statements b).back? with
| none => false
| some s =>
if s.getKind == ``returnStmt then true
else if s.getKind == ``ifStmt then
returns s[2] && !s[3].isNone && returns s[3][1]
else if s.getKind == ``matchStmt then
s[2][0].getArgs.all (fun c => returns c[3])
else false
/-- How statements are lowered: the body of a program, the step of a system that samples
nothing, or the initial bindings with each sample replaced by a value of its law. -/
inductive LowerMode
| program
| system
| template
deriving BEq
def lowerAssignment (s : Syntax) (rest : TSyntax `term)
(calls : Array (Name × TSyntax `term)) (mode : LowerMode) : CommandElabM (TSyntax `term) := do
let names := targetNames s[0]
let pat ← tupleTerm (names.map fun x => ⟨x.raw⟩)
let rhs : TSyntax `term := ⟨s[3]⟩
let called ← if rhs.raw.getKind == ``oracleCall then do
match calls.find? (·.1 == rhs.raw[0].getId) with
| some (_, label) =>
pure (some (label, ← tupleTerm (rhs.raw[2].getSepArgs.map (⟨·⟩))))
| none => pure none
else match rhs with
| `($f:ident $arg) => pure ((calls.find? (·.1 == f.getId)).map fun (_,label) => (label,arg))
| _ => pure none
let value := Lean.mkIdent (← liftCoreM <| mkFreshUserName `value)
let k ← if s[1].isNone then `(fun $value:ident => let $pat:term := $value:ident; $rest)
else `(fun ($value:ident : $(⟨s[1][1]⟩):term) => let $pat:term := $value:ident; $rest)
if s.getKind == ``sampleStmt then
checkPure rhs calls
if mode == .template then return ← `($k (sampleWitness $rhs))
throwErrorAt s "A sampling statement is compiled into a call to its source."
if let some (label,arg) := called then
checkPure arg calls
if mode == .program then return ← `(callProg $label $arg $k)
if mode == .template then
throwErrorAt s "Initialization cannot call inside ports; call them from a procedure."
throwErrorAt s "Inside calls belong to converters."
checkPure rhs calls
if s[1].isNone then return ← `(let $pat:term := $rhs; $rest)
return ← `(let $pat:term : $(⟨s[1][1]⟩):term := $rhs; $rest)
/-- Build ordinary functions of inside histories. Sequencing is substitution of
Lean functions, and a call consumes a history entry. -/
partial def lowerFunction (ss : Array Syntax) (bound persistent : Array Ident)
(calls : Array (Name × TSyntax `term)) (finish : TSyntax `term) (mode : LowerMode) :
CommandElabM (TSyntax `term) := do
if ss.isEmpty then
if finish.raw.isMissing then throwError "Every procedure path must return a reply."
return finish
let s := ss[0]!
let tail := ss.extract 1 ss.size
if s.getKind == ``returnStmt then
if mode == .template then throwErrorAt s "Initialization has no return; its bindings persist."
if !tail.isEmpty then throwErrorAt s "Statements after return are unreachable."
checkPure s[1] calls
let stored ← tupleTerm (persistent.map fun x => ⟨x.raw⟩)
if mode == .program then return ← `(returnProg (some $stored, $(⟨s[1]⟩):term))
return ← `(($stored, $(⟨s[1]⟩):term))
if s.getKind == ``assignStmt || s.getKind == ``sampleStmt then
let mut nextBound := bound
for x in targetNames s[0] do
if !nextBound.any (·.getId == x.getId) then nextBound := nextBound.push x
let rest ← lowerFunction tail nextBound persistent calls finish mode
return ← lowerAssignment s rest calls mode
if tail.isEmpty && s.getKind == ``ifStmt &&
returns s[2] && !s[3].isNone && returns s[3][1] then
checkPure s[1] calls
let yes ← lowerFunction (statements s[2]) bound persistent calls finish mode
let no ← lowerFunction (statements s[3][1]) bound persistent calls finish mode
return ← `(if $(⟨s[1]⟩):term then $yes else $no)
if tail.isEmpty && s.getKind == ``matchStmt &&
s[2][0].getArgs.all (fun c => returns c[3]) then
checkPure s[1] calls
let alts : Array (TSyntax ``Term.matchAlt) ← s[2][0].getArgs.mapM fun c => do
let rhs ← lowerFunction (statements c[3]) bound persistent calls finish mode
`(matchAltExpr| | $(⟨c[1]⟩):term => $rhs)
return ← `(match $(⟨s[1]⟩):term with $alts:matchAlt*)
let rest ← lowerFunction tail bound persistent calls finish mode
let values ← tupleTerm (bound.map fun x => ⟨x.raw⟩)
let received := Lean.mkIdent (← liftCoreM <| mkFreshUserName `bindings)
let next := Lean.mkIdent (← liftCoreM <| mkFreshUserName `next)
let onward ← `($next:ident $values)
let after ← `(fun $received:ident => let $values:term := $received:ident; $rest)
if s.getKind == ``ifStmt then
checkPure s[1] calls
let yes ← lowerFunction (statements s[2]) bound persistent calls onward mode
let no ← if s[3].isNone then pure onward
else lowerFunction (statements s[3][1]) bound persistent calls onward mode
return ← `(let $next:ident := $after; if $(⟨s[1]⟩):term then $yes else $no)
if s.getKind == ``matchStmt then
checkPure s[1] calls
let alts : Array (TSyntax ``Term.matchAlt) ← s[2][0].getArgs.mapM fun c => do
let rhs ← lowerFunction (statements c[3]) bound persistent calls onward mode
`(matchAltExpr| | $(⟨c[1]⟩):term => $rhs)
return ← `(let $next:ident := $after; match $(⟨s[1]⟩):term with $alts:matchAlt*)
if s.getKind == ``forStmt then
checkPure s[3] calls
let x : Ident := ⟨s[1]⟩
if bound.any (·.getId == x.getId) then
throwErrorAt s "Loop variable shadows an existing binding."
let body ← lowerFunction (statements s[4]) (bound.push x) persistent calls onward mode
return ← `(forEach $(⟨s[3]⟩):term
(fun $x:ident $next:ident $received:ident => let $values:term := $received:ident; $body)
$after $values)
throwErrorAt s "Unsupported cryptographic statement."
/-- A sampling site: the source its statement calls, and its law. -/
structure Site where
name : Ident
law : TSyntax `term
/-- The names a statement binds: assignment and sampling targets, and loop variables. -/
partial def boundNames (s : Syntax) : Array Name :=
let own :=
if s.getKind == ``assignStmt || s.getKind == ``sampleStmt then
(targetNames s[0]).map (·.getId)
else if s.getKind == ``forStmt then #[s[1].getId] else #[]
own ++ s.getArgs.flatMap boundNames
/-- Replace the statements of a block. -/
def replaceStatements (b : Syntax) (ss : Array Syntax) : Syntax :=
b.setArg 0 (b[0].setArgs ss)
/-- **Sampling as calls.** Every sampling statement becomes a call to a fresh source, whose law
is recorded; the law may depend on declaration parameters only. -/
partial def desugarSampling (bindings : Array Name) (ss : Array Syntax) :
StateT (Array Site) CommandElabM (Array Syntax) :=
ss.mapM fun s => do
if s.getKind == ``sampleStmt then
let rhs : TSyntax `term := ⟨s[3]⟩
if (identifiers rhs).any fun x => bindings.contains x || bindings.contains x.getRoot then
throwErrorAt rhs "A sampled law may depend on declaration parameters only; sample from a \
fixed law and compute from the sample."
let site := Lean.mkIdent (← liftCoreM <| mkFreshUserName `sample)
modify (·.push ⟨site, rhs⟩)
let call ← `($site:ident ())
return Syntax.node s.getHeadInfo ``assignStmt #[s[0], s[1], Syntax.atom .none " ← ", call.raw]
if s.getKind == ``ifStmt then
let yes ← desugarSampling bindings (statements s[2])
let s := s.setArg 2 (replaceStatements s[2] yes)
if s[3].isNone then return s
let no ← desugarSampling bindings (statements s[3][1])
return s.setArg 3 (s[3].setArg 1 (replaceStatements s[3][1] no))
if s.getKind == ``matchStmt then
let cases ← s[2][0].getArgs.mapM fun c => do
let body ← desugarSampling bindings (statements c[3])
return c.setArg 3 (replaceStatements c[3] body)
return s.setArg 2 (s[2].setArg 0 (s[2][0].setArgs cases))
if s.getKind == ``forStmt then
let body ← desugarSampling bindings (statements s[4])
return s.setArg 4 (replaceStatements s[4] body)
return s
/-- Declaration parameters: explicit names with a type, or instance arguments. -/
def paramBinder (p : Syntax) : CommandElabM (TSyntax ``Term.bracketedBinder) := do
if p.getKind == ``instanceParam then `(bracketedBinder| [$(⟨p[1]⟩):term])
else
let ids : Array Ident := p[1].getArgs.map (⟨·⟩)
`(bracketedBinder| ($ids:ident* : $(⟨p[3]⟩):term))
/-- The explicit parameter names, in order. -/
def paramArgs (ps : Array Syntax) : Array (TSyntax `term) :=
ps.flatMap fun p => if p.getKind == ``instanceParam then #[] else p[1].getArgs.map (⟨·⟩)
/-- The explicit arguments of generated binders, in order. -/
def binderArgs (bs : Array (TSyntax ``Term.bracketedBinder)) : Array (TSyntax `term) :=
bs.flatMap fun b => match b with
| `(bracketedBinder| ($ids:ident* : $_)) => ids.map (⟨·.raw⟩)
| _ => #[]
/-- The names the generated declarations bind for the query budget: `budget` and, on exact
typings, `queries`. They are the only names the elaborator binds without macro scopes, so that
callers can pass the budget by name. -/
def reservedNames : Array Name := #[`budget, `queries]
/-- Reject a component that mentions a reserved name, as a binder or as a reference, so that no
generated binder can capture a name of the component. Every other name the elaborator binds is
hygienic. The name of a named argument, `(budget := k)`, is not a mention. -/
partial def checkReserved (stx : Syntax) : CommandElabM Unit := do
match stx with
| .ident _ _ n _ =>
if reservedNames.contains n.getRoot then
throwErrorAt stx m!"`{n.getRoot}` is reserved: the generated declarations bind it for the \
query budget."
| .node _ kind args =>
if kind == ``Lean.Parser.Term.namedArgument then checkReserved args[3]!
else for a in args do checkReserved a
| _ => pure ()
/-- The identifiers of a piece of syntax, without macro scopes. -/
partial def identsOf : Syntax → Array Name
| .ident _ _ n _ => #[n.eraseMacroScopes]
| .node _ _ args => args.flatMap identsOf
| _ => #[]
/-- The parameters that the types `types` mention, closed under the types and the instance
arguments of the parameters kept. An alphabet takes exactly these, so instance search on the
alphabet at a port determines every argument. -/
def usedParams (params : Array Syntax) (types : Array Syntax) : Array Syntax := Id.run do
let names : Array Name := params.flatMap fun p =>
if p.getKind == ``instanceParam then #[] else p[1].getArgs.map (·.getId)
let mentioned (stx : Syntax) : Array Name := (identsOf stx).filter names.contains
let mut kept : Array Name := (types.flatMap mentioned).foldl
(fun acc n => if acc.contains n then acc else acc.push n) #[]
let mut changed := true
while changed do
changed := false
for p in params do
let deps : Array Name :=
if p.getKind == ``instanceParam then
let ns := mentioned p[1]
if ns.any kept.contains then ns else #[]
else if p[1].getArgs.any (kept.contains ·.getId) then mentioned p[3] else #[]
for n in deps do
unless kept.contains n do
kept := kept.push n
changed := true
return params.filterMap fun p =>
if p.getKind == ``instanceParam then
if (mentioned p[1]).all kept.contains then some p else none
else
let ids := p[1].getArgs.filter (kept.contains ·.getId)
if ids.isEmpty then none else some (p.setArg 1 (mkNullNode ids))
/-- Generate the local labels and their finite input/output families. -/
def declareInterface (name : Ident) (params : Array Syntax)
(ports : Array (Ident × Array Syntax × TSyntax `term)) :
CommandElabM (TSyntax `term × TSyntax `term × TSyntax `term ×
Array (TSyntax ``Term.bracketedBinder) × TSyntax `term × TSyntax `term) := do
let portName := Lean.mkIdent (name.getId ++ `Port)
let ctors ← ports.mapM fun (p, _, _) => `(Lean.Parser.Command.ctor| | $p:ident : $portName:ident)
elabCommand (← `(inductive $portName:ident : Type where $ctors:ctor* deriving DecidableEq))
let values : Array (TSyntax `term) := ports.map fun (p, _, _) =>
⟨(Lean.mkIdent (name.getId ++ `Port ++ p.getId)).raw⟩
-- Instances named in the interface's namespace, so interfaces of one namespace do not clash.
let fintypePort := Lean.mkIdent (name.getId ++ `instFintypePort)
elabCommand (← `(instance $fintypePort:ident : Fintype $portName:ident :=
Fintype.ofList [$values,*] (by intro i; cases i <;> simp)))
if let #[value] := values then
let uniquePort := Lean.mkIdent (name.getId ++ `instUniquePort)
elabCommand (← `(instance $uniquePort:ident : Unique $portName:ident where
default := $value
uniq i := by cases i; rfl))
let binders ← params.mapM paramBinder
-- Each alphabet takes only the parameters its ports mention.
let inParams := usedParams params (ports.flatMap fun (_, arguments, _) => arguments.map (·[2]))
let outParams := usedParams params (ports.map fun (_, _, result) => result.raw)
let inBinders ← inParams.mapM paramBinder
let outBinders ← outParams.mapM paramBinder
let inArgs := paramArgs inParams
let outArgs := paramArgs outParams
let inputName := Lean.mkIdent (name.getId ++ `Input)
let outputName := Lean.mkIdent (name.getId ++ `Output)
let mut ins : Array (TSyntax ``Term.matchAlt) := #[]
let mut outs : Array (TSyntax ``Term.matchAlt) := #[]
for (p, arguments, result) in ports do
let types : Array (TSyntax `term) := arguments.map (fun a => ⟨a[2]⟩)
let mut input ← `(Unit)
if types.size == 1 then input := types[0]!
else if types.size > 1 then
input := types.back!
for t in types.pop.reverse do input ← `($t × $input)
let label := Lean.mkIdent (name.getId ++ `Port ++ p.getId)
ins := ins.push (← `(matchAltExpr| | $label:ident => $input))
outs := outs.push (← `(matchAltExpr| | $label:ident => $result))
elabCommand (← `(abbrev $inputName:ident $inBinders:bracketedBinder* : $portName:ident → Type :=
fun i => match i with $ins:matchAlt*))
elabCommand (← `(abbrev $outputName:ident $outBinders:bracketedBinder* : $portName:ident → Type :=
fun i => match i with $outs:matchAlt*))
let fintypeInput := Lean.mkIdent (name.getId ++ `fintypeInput)
let fintypeOutput := Lean.mkIdent (name.getId ++ `fintypeOutput)
elabCommand (← `(@[reducible] def $fintypeInput:ident $inBinders:bracketedBinder*
(i : $portName:ident) :
Fintype ($inputName:ident $inArgs* i) := by cases i <;> infer_instance))
elabCommand (← `(@[reducible] def $fintypeOutput:ident $outBinders:bracketedBinder*
(i : $portName:ident) :
Fintype ($outputName:ident $outArgs* i) := by cases i <;> infer_instance))
-- With one port, the alphabet at a port reduces to its declared type, whose instances apply;
-- with more, the alphabet at a variable port is found by these instances.
if ports.size ≥ 2 then
elabCommand (← `(attribute [instance] $fintypeInput:ident $fintypeOutput:ident))
return (⟨portName.raw⟩, ← `($inputName:ident $inArgs*), ← `($outputName:ident $outArgs*), binders,
← `($fintypeInput:ident $inArgs*), ← `($fintypeOutput:ident $outArgs*))
/-- An interface declaration: the family of its query budgets. -/
@[command_elab interfaceDecl] def elabInterface : CommandElab := fun stx => do
let ports := stx[3][0].getArgs.map fun p =>
((⟨p[0]⟩ : Ident), p[2].getSepArgs, (⟨p[5]⟩ : TSyntax `term))
let (labels, inputs, outputs, params, fx, fy) ← declareInterface ⟨stx[1]⟩ stx[2].getArgs ports
elabCommand (← `(abbrev $(⟨stx[1]⟩):ident $params:bracketedBinder* (q : ℕ) : Interface :=
@Interface.queryBudget $labels _ $inputs $outputs $fx $fy q))
let perPortName := Lean.mkIdent ((⟨stx[1]⟩ : Ident).getId ++ `perPort)
elabCommand (← `(abbrev $perPortName:ident $params:bracketedBinder*
(q : $labels → ℕ) : Interface :=
@Interface.portBudget $labels _ $inputs $outputs $fx $fy q))
def parameterBinders (ps : Array Syntax) : CommandElabM (Array (TSyntax ``Term.bracketedBinder)) :=
ps.mapM paramBinder
/-- The inside interfaces at budget `k`, with the proof that they admit every nonempty inside
history of at most `k` queries, and the labels of their calls. -/
partial def insideInterfaces (insideDecls : Array Syntax) (used : Array Name) (k : TSyntax `term) :
CommandElabM (TSyntax `term × TSyntax `term × Array (Name × TSyntax `term)) := do
if insideDecls.isEmpty then
return (← `(Interface.unit),
← `(fun xs hne _ => by
cases xs with
| nil => exact absurd rfl hne
| cons x _ => exact x.1.elim), #[])
let first := insideDecls[0]!
let ty : TSyntax `term := ⟨first[3]⟩
let portPrefix := first[1].getId
let mut calls := #[]
let sig ← match ty with
| `($x → $y) =>
calls := #[(portPrefix, ← `(()))]
`(Interface.queryBudget Unit (fun _ => $x) (fun _ => $y) $k)
| _ =>
for id in used do
if id.getPrefix == portPrefix then
let port := Lean.mkIdent (Name.mkSimple id.getString!)
calls := calls.push (id, ← `(.$port:ident))
`($ty $k)
let admits ← `(fun _ hne hl => ⟨hne, hl⟩)
if insideDecls.size == 1 then return (sig, admits, calls)
let (rest, restAdmits, restCalls) ←
insideInterfaces (insideDecls.extract 1 insideDecls.size) used k
let leftCalls ← calls.mapM fun (n,l) => return (n, ← `(Sum.inl $l))
let restCalls ← restCalls.mapM fun (n,l) => return (n, ← `(Sum.inr $l))
return (← `(Interface.tensor $sig $rest), ← `(parallelInputs_of_length_le $admits $restAdmits),
leftCalls ++ restCalls)
/-- The number of inside calls of a procedure body, as a function of its inputs: calls count
one, branches and matches choose, and a loop multiplies its body's count by its length. -/
partial def costOf (ss : Array Syntax) (calls : Array (Name × TSyntax `term)) :
CommandElabM (TSyntax `term) := do
if ss.isEmpty then return ← `(0)
let s := ss[0]!
let tail := ss.extract 1 ss.size
if s.getKind == ``returnStmt then return ← `(0)
if s.getKind == ``sampleStmt then return ← costOf tail calls
if s.getKind == ``assignStmt then
let rhs : TSyntax `term := ⟨s[3]⟩
let called := (rhs.raw.getKind == ``oracleCall && calls.any (·.1 == rhs.raw[0].getId)) ||
(match rhs with
| `($f:ident $_) => calls.any (·.1 == f.getId)
| _ => false)
let rest ← costOf tail calls
if called then return ← `(1 + $rest)
let pat ← tupleTerm (targetNames s[0] |>.map fun x => ⟨x.raw⟩)
if s[1].isNone then return ← `(let $pat:term := $rhs; $rest)
return ← `(let $pat:term : $(⟨s[1][1]⟩):term := $rhs; $rest)
if s.getKind == ``ifStmt then
let yes ← costOf (statements s[2]) calls
let no ← if s[3].isNone then `(0) else costOf (statements s[3][1]) calls
let rest ← costOf tail calls
return ← `((if $(⟨s[1]⟩):term then $yes else $no) + $rest)
if s.getKind == ``matchStmt then
let alts : Array (TSyntax ``Term.matchAlt) ← s[2][0].getArgs.mapM fun c => do
let rhs ← costOf (statements c[3]) calls
`(matchAltExpr| | $(⟨c[1]⟩):term => $rhs)
let rest ← costOf tail calls
return ← `((match $(⟨s[1]⟩):term with $alts:matchAlt*) + $rest)
if s.getKind == ``forStmt then
let body ← costOf (statements s[4]) calls
let rest ← costOf tail calls
return ← `($rest + ($(⟨s[3]⟩):term).length * $body)
throwErrorAt s "Unsupported cryptographic statement."
/-- The most inside calls along a path of a procedure body: a call counts one, branches and
matches take the largest of their counts, and a loop over a displayed list `[a₁, …, aₙ]`
multiplies its body's count by `n`. A loop over any other list has no constant count. -/
partial def callCount (ss : Array Syntax) (calls : Array (Name × TSyntax `term)) : Option Nat := do
if ss.isEmpty then return 0
let s := ss[0]!
let tail := ss.extract 1 ss.size
if s.getKind == ``returnStmt then return 0
if s.getKind == ``assignStmt then
let rhs : TSyntax `term := ⟨s[3]⟩
let called := (rhs.raw.getKind == ``oracleCall && calls.any (·.1 == rhs.raw[0].getId)) ||
(match rhs with
| `($f:ident $_) => calls.any (·.1 == f.getId)
| _ => false)
return (if called then 1 else 0) + (← callCount tail calls)
if s.getKind == ``forStmt then
match (⟨s[3]⟩ : TSyntax `term) with
| `([$items,*]) =>
return items.getElems.size * (← callCount (statements s[4]) calls) +
(← callCount tail calls)
| _ => none
if s.getKind == ``ifStmt then
let yes ← callCount (statements s[2]) calls
let no ← if s[3].isNone then pure 0 else callCount (statements s[3][1]) calls
return max yes no + (← callCount tail calls)
if s.getKind == ``matchStmt then
let counts ← s[2][0].getArgs.mapM fun c => callCount (statements c[3]) calls
return counts.foldl max 0 + (← callCount tail calls)
none
/-- The number of error messages logged so far. -/
def errorCount : CommandElabM Nat := do
return (← get).messages.toList.countP (·.severity == .error)
/-- What determines a component's outside interface at every budget: a declared interface
family, named components of an ordered tensor, or generated labels and finite alphabets with
an optional exact domain. -/
structure Signature where
declared : Option (TSyntax `term)
/-- The named outside components and their interface families, in declaration order. -/
outside : Array (Ident × TSyntax `term) := #[]
labels : TSyntax `term
inputs : TSyntax `term
outputs : TSyntax `term
fintypeInputs : TSyntax `term
fintypeOutputs : TSyntax `term
exactDomain : Option (Ident × TSyntax `term × TSyntax `term)
/-- A budget for each of `n` named outside components, nested to the right in declaration order:
`ℕ × (ℕ × ℕ)` for three, and `ℕ` for one component or none. -/
partial def outsideBudgetType (n : Nat) : CommandElabM (TSyntax `term) := do
if n ≤ 1 then `(ℕ) else `(ℕ × $(← outsideBudgetType (n - 1)))
/-- Zero queries at every named outside component, of type `outsideBudgetType n`. -/
partial def outsideZeroBudget (n : Nat) : CommandElabM (TSyntax `term) := do
if n ≤ 1 then `(0) else `((0, $(← outsideZeroBudget (n - 1))))
/-- The ordered tensor of the named components' interfaces, each at its own entry of the budget
tuple `q`: `A q.1 ⊗ (B q.2.1 ⊗ C q.2.2)` for three, `A q` for one. -/
partial def outsideAt (outside : Array (Ident × TSyntax `term)) (q : TSyntax `term) :
CommandElabM (TSyntax `term) := do
if outside.isEmpty then throwError "Declare at least one outside component."
let sig := outside[0]!.2
if outside.size == 1 then return ← `($sig $q)
let rest ← outsideAt (outside.extract 1 outside.size) (← `(($q).2))
`(Interface.tensor ($sig ($q).1) $rest)
/-- The label of a procedure `c.p` in the ordered tensor: the port `.p` of component `c`, as
`.inl .p` when `c` is the first of several components and behind `.inr` when it is later; one
component keeps `.p`. A missing or unknown prefix is rejected. -/
partial def outsideLabel (outside : Array (Ident × TSyntax `term)) (procedure : Ident) :
CommandElabM (TSyntax `term) := do
if outside.isEmpty then throwErrorAt procedure "Unknown outside component in procedure name."
if procedure.getId.getPrefix == outside[0]!.1.getId then
let port := Lean.mkIdent (Name.mkSimple procedure.getId.getString!)
let label ← `(.$port:ident)
if outside.size == 1 then return label
return ← `(Sum.inl $label)
let label ← outsideLabel (outside.extract 1 outside.size) procedure
`(Sum.inr $label)
/-- The procedure's label in its ordered tensor, declared interface or generated interface. -/
def Signature.label (σ : Signature) (name procedure : Ident) : CommandElabM (TSyntax `term) := do
if !σ.outside.isEmpty then return ← outsideLabel σ.outside procedure
if σ.declared.isSome then return ← `(.$procedure:ident)
return ⟨(Lean.mkIdent (name.getId ++ `Port ++ procedure.getId)).raw⟩
/-- The outside interface at budget `k`, a tuple for several named components. -/
def Signature.at (σ : Signature) (k : TSyntax `term) : CommandElabM (TSyntax `term) := do
if !σ.outside.isEmpty then return ← outsideAt σ.outside k
if let some sig := σ.declared then return ← `(($sig $k))
let labels := σ.labels
let inputs := σ.inputs
let outputs := σ.outputs
let fx := σ.fintypeInputs
let fy := σ.fintypeOutputs
match σ.exactDomain with
| none => `(@Interface.queryBudget $labels _ $inputs $outputs $fx $fy $k)
| some (x, predicate, proof) =>
`(({ I := $labels, X := $inputs, Y := $outputs, instFintypeX := $fx, instFintypeY := $fy,
«domain» := fun h => (fun $x:ident => $predicate) h ∧ h.length ≤ $k,
nonempty_prefix := budget_nonempty_prefix (P := fun $x:ident => $predicate) $proof,
bound := $k, length_le := fun _ hd => hd.2 } : Interface))
/-- The interface alphabets, independent of the outside budgets. -/
def Signature.zero (σ : Signature) : CommandElabM (TSyntax `term) := do
σ.at (← outsideZeroBudget σ.outside.size)
/-- The outside interface at the per-port budget `q`, when the component has one: a declared
interface family, its generated labels without an exact domain, or named components each with a
declared family. Named components restrict `q` along their tags:
`A.perPort (fun i => q (.inl i)) ⊗ B.perPort (fun i => q (.inr i))` for two. -/
partial def Signature.perPortAt (σ : Signature) (q : TSyntax `term) :
CommandElabM (Option (TSyntax `term)) := do
if !σ.outside.isEmpty then
let first : Signature := { σ with declared := some σ.outside[0]!.2, outside := #[] }
if σ.outside.size == 1 then return ← first.perPortAt q
let some left ← first.perPortAt (← `(fun i => $q (Sum.inl i))) | return none
let rest := { σ with outside := σ.outside.extract 1 σ.outside.size }
let some right ← rest.perPortAt (← `(fun i => $q (Sum.inr i))) | return none
return some (← `(Interface.tensor $left $right))
if let some sig := σ.declared then
match sig with
| `(($inner)) => return ← ({ σ with declared := some inner } : Signature).perPortAt q
| `($f:ident $args*) => return some (← `($(Lean.mkIdent (f.getId ++ `perPort)) $args* $q))
| `($f:ident) => return some (← `($(Lean.mkIdent (f.getId ++ `perPort)) $q))
| _ => return none
if σ.exactDomain.isSome then return none
return some (← `(@Interface.portBudget $(σ.labels) _ $(σ.inputs) $(σ.outputs)
$(σ.fintypeInputs) $(σ.fintypeOutputs) $q))
/-- The inside interfaces of a component at budget `k`, with the proof that they admit every
nonempty history of at most `k` queries, and the labels of their calls: the declared inside
interfaces, then the sources of the sampling sites. -/
def componentInside (converting : Bool) (insides sites : Array Syntax) (used : Array Name)
(k : TSyntax `term) :
CommandElabM (TSyntax `term × TSyntax `term × Array (Name × TSyntax `term)) := do
if sites.isEmpty then return ← insideInterfaces insides used k
let (rand, randAdmits, randCalls) ← insideInterfaces sites used k
if !converting then return (rand, randAdmits, randCalls)
let (declared, declaredAdmits, declaredCalls) ← insideInterfaces insides used k
let leftCalls ← declaredCalls.mapM fun (n, l) => return (n, ← `(Sum.inl $l))
let rightCalls ← randCalls.mapM fun (n, l) => return (n, ← `(Sum.inr $l))
return (← `(Interface.tensor $declared $rand),
← `(parallelInputs_of_length_le $declaredAdmits $randAdmits), leftCalls ++ rightCalls)
/-- The port map of a converter with one declared inside interface: for each procedure, the
inside label it calls, if any, with that label's name. It exists when each procedure calls at
most one inside label and distinct procedures call distinct labels. -/
def insidePortMap (oracles : Array Syntax) (calls : Array (Name × TSyntax `term)) :
Option (Array (Ident × Option (Name × TSyntax `term))) := Id.run do
let mut entries := #[]
let mut taken : Array Name := #[]
for p in oracles do
let called := (identifiers p).foldl (fun acc n =>
match calls.find? (·.1 == n) with
| some c => if acc.any (·.1 == c.1) then acc else acc.push c
| none => acc) #[]
if called.size > 1 then return none
let entry := called[0]?
if let some c := entry then
if taken.contains c.1 then return none
taken := taken.push c.1
entries := entries.push ((⟨p[1]⟩ : Ident), entry)
return some entries
/-- The per-port typing of a component: a system at every per-port budget; a converter with
named outside components, into its inside interfaces at the aggregate allowance
`bound · (outside per-port interface).bound`; and a converter with an annotated outside interface
whose single inside port has that interface, when each procedure calls only its own
inside port, at most once; or whose single inside port has another interface, each of whose
labels one procedure calls, at most once, the other procedures calling none: its budget at a
label is that procedure's (`insideBudget`), along the port map `portMap`. The declarations are
kept only if they elaborate. -/
def elabPerPortDecls (converting : Bool) (name : Ident)
(params : Array (TSyntax ``Term.bracketedBinder)) (σ : Signature)
(insides sites oracles : Array Syntax) (used : Array Name) : CommandElabM Unit := do
let q := Lean.mkIdent `budget
let some sigPP ← σ.perPortAt q | return
let args := binderArgs params
let sigZero ← σ.zero
let bodyName := Lean.mkIdent (name.getId ++ `body)
let boundName := Lean.mkIdent (name.getId ++ `bound)
let boundSpecName := Lean.mkIdent (name.getId ++ `bound_spec)
let randomnessName := Lean.mkIdent (name.getId ++ `randomness)
let preservingName := Lean.mkIdent (name.getId ++ `preserving)
let programName := Lean.mkIdent (name.getId ++ `perPortProgram)
let perPortName := Lean.mkIdent (name.getId ++ `perPort)
-- The inside allowance: the bound times the total of the per-port budgets.
let k ← if σ.outside.isEmpty then `($boundName $args* * ∑ i, $q i)
else `($boundName $args* * ($sigPP).bound)
let saved ← get
let before ← errorCount
try
-- Systems, and converters with named outside components, use the aggregate allowance `k`.
if !converting || !σ.outside.isEmpty then
let (innerK, admitsK, _) ← componentInside converting insides sites used k
let program ← `((TypedConverter.ofProgram none ($bodyName $args*) ($boundSpecName $args*)
$admitsK : $sigPP ⟶ $innerK))
if converting then
let (declK, _, _) ← insideInterfaces insides used k
let result ← if sites.isEmpty then pure program else
`($program ≫ TypedConverter.rightContext $declK ($randomnessName $args* $k))
elabCommand (← `(noncomputable def $perPortName:ident $params:bracketedBinder*
{$q : ($sigZero).I → ℕ} : $sigPP ⟶ $declK := $result))
else
elabCommand (← `(noncomputable def $perPortName:ident $params:bracketedBinder*
{$q : ($sigZero).I → ℕ} : TypedSystem $sigPP :=
$program • $randomnessName $args* $k))
else
let some declared := σ.declared | return
unless insides.size == 1 do return
let insideTy : TSyntax `term := ⟨(insides[0]!)[3]⟩
let wrap (l : TSyntax `term) : CommandElabM (TSyntax `term) :=
if sites.isEmpty then pure l else `(Sum.inl $l)
-- The inside interface at its per-port budget `qIn`, the port map `ι`, and, for an inside
-- history within the budgets of the port map, its budget at each inside label.
let (insidePP, qIn, ι, within) ← if insideTy.raw.structEq declared.raw then
let o := Lean.mkIdent `o
pure (sigPP, ← `($q), ← `(fun $o:ident => some $(← wrap o)),
← `(fun $o:ident => hc $o:ident _ rfl))
else do
let (_, _, declaredCalls) ← insideInterfaces insides used (← `(0))
let some entries := insidePortMap oracles declaredCalls | return
let qAlts ← entries.filterMapM fun (o, e) => e.mapM fun (_, l) =>
`(Term.matchAltExpr| | $l => $q .$o:ident)
let insideBudgetName := Lean.mkIdent (name.getId ++ `insideBudget)
let qIn ← `($insideBudgetName $args* $q)
let some insidePP ← ({ σ with declared := some insideTy } : Signature).perPortAt qIn
| return
elabCommand (← `(def $insideBudgetName:ident $params:bracketedBinder*
($q : ($sigZero).I → ℕ) : ($insideTy 0).I → ℕ :=
fun j => match j with $qAlts:matchAlt*))
let ιAlts ← entries.mapM fun (o, e) => do
match e with
| some (_, l) => `(Term.matchAltExpr| | .$o:ident => some $(← wrap l))
| none => `(Term.matchAltExpr| | .$o:ident => none)
let withinAlts ← entries.filterMapM fun (o, e) => e.mapM fun (_, l) =>
`(Term.matchAltExpr| | $l => hc .$o:ident _ rfl)
pure (insidePP, qIn, ← `(fun o => match o with $ιAlts:matchAlt*),
← `(fun j => match j with $withinAlts:matchAlt*))
let (innerZero, _, _) ← componentInside converting insides sites used (← `(0))
let portMapName := Lean.mkIdent (name.getId ++ `portMap)
elabCommand (← `(def $portMapName:ident $params:bracketedBinder* :
($sigZero).I → Option ($innerZero).I := $ι))
elabCommand (← `(set_option Elab.async false in
theorem $preservingName:ident $params:bracketedBinder* :
($bodyName $args*).PortPreserving ($portMapName $args*) := by
unfold $bodyName:ident $portMapName:ident
program_preserving))
let (innerPP, admitsPP) ← if sites.isEmpty then
pure (insidePP, ← `(fun _ hne _ hc => ⟨hne, $within⟩))
else do
let (randK, admitsK, _) ← insideInterfaces sites used k
pure (← `(Interface.tensor $insidePP $randK),
← `(fun ys hne hl hc => Interface.perPort_tensor_admits (A := $insidePP) (B := $randK)
$qIn (fun _ hne' hc' => ⟨hne', hc'⟩) $admitsK ys hne hl $within))
elabCommand (← `(noncomputable def $programName:ident $params:bracketedBinder*
{$q : ($sigZero).I → ℕ} : $sigPP ⟶ $innerPP :=
TypedConverter.ofPreservingProgram none ($bodyName $args*) ($boundSpecName $args*)
($portMapName $args*) ($preservingName $args*) $q (fun _ hd => hd.2) $admitsPP))
if sites.isEmpty then
elabCommand (← `(noncomputable def $perPortName:ident $params:bracketedBinder*
{$q : ($sigZero).I → ℕ} : $sigPP ⟶ $insidePP := $programName $args* (budget := $q)))
else
elabCommand (← `(noncomputable def $perPortName:ident $params:bracketedBinder*
{$q : ($sigZero).I → ℕ} : $sigPP ⟶ $insidePP :=
CategoryTheory.CategoryStruct.comp ($programName $args* (budget := $q))
(TypedConverter.rightContext $insidePP ($randomnessName $args* $k))))
if (← errorCount) > before then set saved
catch _ => set saved
/-- The inside interface of a sampling site: a source of the law's type. -/
def siteDecl (site : Site) (lawName : Ident) (args : Array (TSyntax `term)) :
CommandElabM Syntax := do
let ty ← `(Unit → lawType ($lawName $args*))
return Syntax.node .none ``insideDecl
#[Syntax.atom .none "inside ", site.name.raw, Syntax.atom .none " : ", ty.raw]
/-- The parallel composition of the sources of the sites at budget `k`. -/
def sourcesAt (lawNames : Array Ident) (args : Array (TSyntax `term)) (k : TSyntax `term) :
CommandElabM (TSyntax `term) := do
let mut result ← `(TypedSystem.source ($(lawNames.back!) $args*) $k)
for law in lawNames.pop.reverse do
result ← `(TypedSystem.parallel (TypedSystem.source ($law $args*) $k) $result)
return result
/-- The declarations of a component compiled to a program: its body, its inferred per-call
bound, its program from the outside interface `A` to `bound · A.bound` inside queries,
and its sources. The result records whether the displayed constant bound was proved. -/
def elabProgramDecls (converting : Bool) (name : Ident)
(params : Array (TSyntax ``Term.bracketedBinder))
(σ : Signature) (insides sites : Array Syntax) (lawNames : Array Ident) (used : Array Name)
(state : Ident) (alts : Array (TSyntax ``Term.matchAlt)) (innerZero stateTy : TSyntax `term)
(displayedBound : Option Nat) : CommandElabM Bool := do
let args := binderArgs params
let budget := Lean.mkIdent `budget
let budgetType ← outsideBudgetType σ.outside.size
let sigZero ← σ.zero
let bodyName := Lean.mkIdent (name.getId ++ `body)
let boundedName := Lean.mkIdent (name.getId ++ `bounded)
let boundName := Lean.mkIdent (name.getId ++ `bound)
let boundSpecName := Lean.mkIdent (name.getId ++ `bound_spec)
let programName := Lean.mkIdent (name.getId ++ `program)
let randomnessName := Lean.mkIdent (name.getId ++ `randomness)
elabCommand (← `(noncomputable def $bodyName:ident $params:bracketedBinder* :
Program (Option $stateTy) ($sigZero).I ($innerZero).I ($sigZero).X
($sigZero).Y ($innerZero).X ($innerZero).Y :=
fun $state:ident i => match i with $alts:matchAlt*))
-- The bound read off the displayed calls, when every loop runs over a displayed list.
-- Its proof first reduces the literal fold `forEach [a₁, …, aₙ]`, then runs `program_bound`;
-- otherwise the bound is inferred below.
let mut displayed := false
if let some n := displayedBound then
let saved ← get
let before ← errorCount
try
elabCommand (← `(abbrev $boundName:ident $params:bracketedBinder* : ℕ := $(quote n)))
elabCommand (← `(set_option Elab.async false in
theorem $boundSpecName:ident $params:bracketedBinder* :
($bodyName $args*).Bounded ($boundName $args*) := by
unfold $bodyName:ident
intro s i x
component_cases i <;>
dsimp -failIfUnchanged only [forEach, List.foldr_cons, List.foldr_nil] <;>
dsimp -failIfUnchanged <;> program_bound))
if (← errorCount) > before then set saved else displayed := true
catch _ => set saved
unless displayed do
elabCommand (← `(theorem $boundedName:ident $params:bracketedBinder* :
∃ b, ($bodyName $args*).Bounded b := by
unfold $bodyName:ident
program_bounded $sigZero))
elabCommand (← `(noncomputable def $boundName:ident $params:bracketedBinder* : ℕ :=
@Nat.find _ (Classical.decPred _) ($boundedName $args*)))
elabCommand (← `(theorem $boundSpecName:ident $params:bracketedBinder* :
($bodyName $args*).Bounded ($boundName $args*) :=
@Nat.find_spec _ (Classical.decPred _) ($boundedName $args*)))
let sigB ← σ.at budget
-- The inside allowance `bound · A.bound`: for a budget tuple, the bound times its total.
let k ← if σ.outside.isEmpty then `($boundName $args* * $budget)
else `($boundName $args* * ($sigB).bound)
let (innerK, admitsK, _) ← componentInside converting insides sites used k
let bodyAt := Lean.mkIdent (name.getId ++ `bodyAt)
if converting then
-- Name the same body at this budget's interfaces, including the sources of fresh draws.
elabCommand (← `(
/-- The declared program at this budget, including its inside random sources. -/
noncomputable abbrev $bodyAt:ident $params:bracketedBinder*
($budget : $budgetType) :
Program (Option $stateTy) ($sigB).I ($innerK).I ($sigB).X ($sigB).Y
($innerK).X ($innerK).Y := $bodyName $args*))
elabCommand (← `(noncomputable def $programName:ident $params:bracketedBinder*
{$budget : $budgetType} :
$sigB ⟶ $innerK :=
TypedConverter.ofProgram none ($bodyName $args*) ($boundSpecName $args*) $admitsK))
if !sites.isEmpty then
-- A hygienic name, so the budget of the sources captures no parameter of the component.
let q := Lean.mkIdent (← liftMacroM (Lean.Macro.addMacroScope `sourceBudget))
let (randQ, _, _) ← insideInterfaces sites used q
elabCommand (← `(noncomputable def $randomnessName:ident $params:bracketedBinder* ($q : ℕ) :
TypedSystem $randQ := $(← sourcesAt lawNames args q)))
if converting then
let (declK, _, _) ← insideInterfaces insides used k
if sites.isEmpty then
elabCommand (← `(noncomputable def $name:ident $params:bracketedBinder*
{$budget : $budgetType} :
$sigB ⟶ $declK := $programName $args* (budget := $budget)))
-- Expose the body at the caller's budget. The generated program supplies both certificates.
let eqName := Lean.mkIdent (name.getId ++ `eq_ofProgram)
elabCommand (← `(
/-- The converter is its declared program, before initialization, at this budget. -/
theorem $eqName:ident $params:bracketedBinder* {$budget : $budgetType} :
($name $args* (budget := $budget) : $sigB ⟶ $declK) =
TypedConverter.ofProgram (A := $sigB) (B := $declK) none ($bodyName $args*)
($boundSpecName $args*) $admitsK := rfl))
else
elabCommand (← `(noncomputable def $name:ident $params:bracketedBinder*
{$budget : $budgetType} :
$sigB ⟶ $declK :=
CategoryTheory.CategoryStruct.comp ($programName $args* (budget := $budget))
(TypedConverter.rightContext $declK ($randomnessName $args* $k))))
else
elabCommand (← `(noncomputable def $name:ident $params:bracketedBinder*
{$budget : $budgetType} :
TypedSystem $sigB :=
$programName $args* (budget := $budget) • $randomnessName $args* $k))
return displayed
/-- The exact typing of a converter that samples nothing, when its number of inside calls is
a function of the input: the outside interface at query budget `queries` (a tuple for several
named components), restricted to histories of total cost at most `budget`, into `budget` inside
queries. The declarations are kept only if the inferred count elaborates and is proved. -/
def elabExactDecls (name : Ident) (params : Array (TSyntax ``Term.bracketedBinder))
(σ : Signature) (insides : Array Syntax) (used : Array Name)
(oracles : Array Syntax) (bodies : Array (Array Syntax))
(calls : Array (Name × TSyntax `term)) (input : Ident) : CommandElabM Unit := do
let args := binderArgs params
let budget := Lean.mkIdent `budget
let queries := Lean.mkIdent `queries
let budgetType ← outsideBudgetType σ.outside.size
let sigZero ← σ.zero
let bodyName := Lean.mkIdent (name.getId ++ `body)
let boundSpecName := Lean.mkIdent (name.getId ++ `bound_spec)
let costName := Lean.mkIdent (name.getId ++ `cost)
let costsName := Lean.mkIdent (name.getId ++ `costs)
let exactName := Lean.mkIdent (name.getId ++ `exact)
let saved ← get
let before ← errorCount
try
let mut costAlts : Array (TSyntax ``Term.matchAlt) := #[]
for (procedure, body) in oracles.zip bodies do
let procArgs : Array Ident := procedure[3].getSepArgs.map (fun a => ⟨a[0]⟩)
let label ← σ.label name ⟨procedure[1]⟩
let mut c ← costOf body calls
if !procArgs.isEmpty then
let pat ← tupleTerm (procArgs.map fun x => ⟨x.raw⟩)
c ← `(let $pat:term := $input:ident; $c)
costAlts := costAlts.push (← `(matchAltExpr| | $label:term => fun $input:ident => ($c : ℕ)))
elabCommand (← `(noncomputable def $costName:ident $params:bracketedBinder* :
∀ i, ($sigZero).X i → ℕ := fun i => match i with $costAlts:matchAlt*))
elabCommand (← `(set_option Elab.async false in
theorem $costsName:ident $params:bracketedBinder* :
($bodyName $args*).Costs (fun x => $costName $args* x.1 x.2) := by
intro s i x
component_cases i <;> simp only [$bodyName:ident, $costName:ident] <;> program_cost))
let (innerB, admitsB, _) ← insideInterfaces insides used budget
let sigQ ← σ.at queries
let outside ← `(Interface.restrict $sigQ
(fun h => (h.map fun x => $costName $args* x.1 x.2).sum ≤ $budget) (cost_prefix_closed _ _))
elabCommand (← `(noncomputable def $exactName:ident $params:bracketedBinder*
{$budget : ℕ} {$queries : $budgetType} : $outside ⟶ $innerB :=
TypedConverter.ofCostedProgram none ($bodyName $args*) ($boundSpecName $args*)
(fun x => $costName $args* x.1 x.2) ($costsName $args*) (fun _ hd => hd.2) $admitsB))
if (← errorCount) > before then set saved
catch _ => set saved
/-- The port label, the input type and the reply type of a procedure. -/
def procedureSignature (name : Ident) (σ : Signature) (persistent : Array Ident)
(procedure : Syntax) :
CommandElabM (Array Ident × TSyntax `term × TSyntax `term × TSyntax `term) := do
if !returns procedure[7] then throwErrorAt procedure "Every procedure path must return a reply."
let procArgs : Array Ident := procedure[3].getSepArgs.map (fun a => ⟨a[0]⟩)
for a in procArgs do
if persistent.any (·.getId == a.getId) then
throwErrorAt a "Oracle parameter shadows persistent binding."
let label ← σ.label name ⟨procedure[1]⟩
let types : Array (TSyntax `term) := procedure[3].getSepArgs.map (fun a => ⟨a[2]⟩)
let mut argType ← `(Unit)
if !types.isEmpty then
argType := types.back!
for t in types.pop.reverse do argType ← `($t × $argType)
return (procArgs, label, argType, ⟨procedure[6]⟩)
/-- The step of a procedure of a system that samples nothing. -/
def systemAlt (name : Ident) (σ : Signature) (persistent : Array Ident) (stored : TSyntax `term)
(state input : Ident) (procedure : Syntax) : CommandElabM (TSyntax ``Term.matchAlt) := do
let (procArgs, label, argType, resultType) ← procedureSignature name σ persistent procedure
let checkedBody ← annotateReturns procedure[7] resultType
let mut body ← lowerFunction (statements checkedBody) (persistent ++ procArgs) persistent
#[] ⟨.missing⟩ .system
if !procArgs.isEmpty then
let pat ← tupleTerm (procArgs.map fun x => ⟨x.raw⟩)
body ← `(let $pat:term := $input:ident; $body)
if !persistent.isEmpty then body ← `(let $stored:term := $state:ident; $body)
`(matchAltExpr| | $label:term => fun ($input:ident : $argType) => ($body : _ × $resultType))
/-- The program of a procedure: initialization first when no bindings are stored yet. -/
def programAlt (name : Ident) (σ : Signature) (persistent : Array Ident) (stored : TSyntax `term)
(state input : Ident) (calls : Array (Name × TSyntax `term)) (initD : Array Syntax)
(resultOf : TSyntax `term → CommandElabM (TSyntax `term)) (procedure : Syntax)
(bodyD : Array Syntax) : CommandElabM (TSyntax ``Term.matchAlt) := do
let (procArgs, label, argType, resultType) ← procedureSignature name σ persistent procedure
let checked ← bodyD.mapM (annotateReturns · resultType)
let resumed ← lowerFunction checked (persistent ++ procArgs) persistent calls ⟨.missing⟩ .program
-- With no initialization the same procedure runs at every invocation.
let mut body := resumed
unless initD.isEmpty do
let first ← lowerFunction (initD ++ checked) procArgs persistent calls ⟨.missing⟩ .program
body ← `(match $state:ident with
| some $stored:term => $resumed
| none => $first)
if !procArgs.isEmpty then
let pat ← tupleTerm (procArgs.map fun x => ⟨x.raw⟩)
body ← `(let $pat:term := $input:ident; $body)
`(matchAltExpr| | $label:term => fun ($input:ident : $argType) =>
($body : $(← resultOf resultType)))
/-- Register the wrappers this declaration generated in `component_definitions`, which `inline`
expands automatically. Bodies, pure functions and initial values stay named objects. -/
def registerComponentDefinitions (name : Ident) (before : Environment) : CommandElabM Unit := do
let owner := (← getCurrNamespace) ++ name.getId
for suffix in [Name.anonymous, `program, `perPort, `perPortProgram, `randomness, `exact] do
let decl := owner ++ suffix
if !before.contains decl && (← getEnv).contains decl then
elabCommand (← `(attribute [component_definitions] $(Lean.mkIdent decl):ident))
/-- The equations of each procedure, at its concrete label: for a system that samples nothing,
its step; for a program, its body and, when the displayed bound was proved, its `combine` and
memoryless reply law. Initialization and later calls have separate equations, so a retained
sample is never replaced by a fresh one. Loops over symbolic lists stay folds. -/
def elabComponentEquations (name : Ident) (params : Array (TSyntax ``Term.bracketedBinder))
(σ : Signature) (oracles : Array Syntax) (stateTy : TSyntax `term)
(inner : Option (TSyntax `term)) (normalizeInvocation : Bool := true)
(statelessConverter : Bool := false) : CommandElabM Unit := do
let args := binderArgs params
let body := Lean.mkIdent (name.getId ++ `body)
let step := Lean.mkIdent (name.getId ++ `step)
let bound := Lean.mkIdent (name.getId ++ `bound)
let spec := Lean.mkIdent (name.getId ++ `bound_spec)
let state := Lean.mkIdent (← liftCoreM <| mkFreshUserName `state)
let input := Lean.mkIdent (← liftCoreM <| mkFreshUserName `input)
let insideState := Lean.mkIdent (← liftCoreM <| mkFreshUserName `InsideState)
let insideStep := Lean.mkIdent (← liftCoreM <| mkFreshUserName `insideStep)
let insideValue := Lean.mkIdent (← liftCoreM <| mkFreshUserName `insideState)
let law := Lean.mkIdent (← liftCoreM <| mkFreshUserName `law)
let outer ← σ.zero
for procedure in oracles do
let proc : Ident := ⟨procedure[1]⟩
let label ← σ.label name proc
let owner := name.getId ++ proc.getId.getPrefix
let suffix := proc.getId.getString!
if let some inner := inner then
let history := Lean.mkIdent (← liftCoreM <| mkFreshUserName `exchanges)
if statelessConverter then
-- Keep the phase equations of a sibling port, e.g. `get` beside `get_initial`.
let usesPhaseName := oracles.any fun other =>
let port := other[1].getId
port.getPrefix == proc.getId.getPrefix &&
(suffix == port.getString! ++ "_initial" || suffix == port.getString! ++ "_resumed")
let bodyEq := Lean.mkIdent (if usesPhaseName then name.getId ++ proc.getId ++ `body
else owner ++ Name.mkSimple ("body_" ++ suffix))
elabCommand (← `(component_equation $bodyEq:ident $params:bracketedBinder*
($state : Option $stateTy) ($input : ($outer).X $label)
($history : List ((Sigma ($inner).X) × (Sigma ($inner).Y))) :
$body $args* $state $label $input $history using $body:ident))
for initial in [true, false] do
let stateBinders ← if initial then pure #[]
else pure #[← `(bracketedBinder| ($state : $stateTy))]
let current ← if initial then `(none) else `(some $state:ident)
let phase := if initial then "_initial" else "_resumed"
let bodyEq := Lean.mkIdent (owner ++ Name.mkSimple ("body_" ++ suffix ++ phase))
elabCommand (← `(component_equation $bodyEq:ident $params:bracketedBinder*
$stateBinders:bracketedBinder* ($input : ($outer).X $label)
($history : List ((Sigma ($inner).X) × (Sigma ($inner).Y))) :
$body $args* $current $label $input $history using $body:ident))
unless normalizeInvocation do continue
let combineEq := Lean.mkIdent
(owner ++ Name.mkSimple ("combine_" ++ suffix ++ phase))