-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathlean.rs
More file actions
2235 lines (2140 loc) · 92.5 KB
/
Copy pathlean.rs
File metadata and controls
2235 lines (2140 loc) · 92.5 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
//! The Lean backend
//!
//! This module defines the trait implementations to export the rust ast to
//! Pretty::Doc type, which can in turn be exported to string (or, eventually,
//! source maps).
use std::collections::HashSet;
use std::sync::OnceLock;
use super::prelude::*;
use crate::{
ast::{
identifiers::global_id::view::{ConstructorKind, PathSegment, TypeDefKind},
span::Span,
},
attributes::hax_proof_attributes,
names::rust_primitives::hax::{
cast_op,
explicit_monadic::{lift, pure},
},
phase::*,
};
use camino::Utf8PathBuf;
use hax_lib_macros_types::ProofMethod;
use hax_types::engine_api::File;
mod binops {
pub use crate::names::core::cmp::PartialEq;
pub use crate::names::core::ops::bit::*;
pub use crate::names::core::ops::index::*;
pub use crate::names::rust_primitives::arithmetic::neg;
pub use crate::names::rust_primitives::hax::machine_int::*;
pub use crate::names::rust_primitives::hax::{logical_op_and, logical_op_or};
}
const LIFT: GlobalId = lift;
const PURE: GlobalId = pure;
const CAST_OP: GlobalId = cast_op;
/// The Lean printer
#[setup_printer_struct]
#[derive(Default, Clone)]
pub struct LeanPrinter {
current_namespace: Option<GlobalId>,
/// The trait whose body is currently being emitted, if any. Set by
/// [`PrettyAst::item`] when entering an [`ItemKind::Trait`] and threaded
/// through trait-item rendering. Used by the [`ExprKind::App`] fallback to
/// detect intra-trait calls (i.e. `Self::F` where `F` is a sibling field of
/// the trait being declared) and drop the qualification, since Lean class
/// elaboration resolves sibling field names within the same `where` block.
current_trait: Option<GlobalId>,
}
const INDENT: isize = 2;
const HEADER: &str = "
-- Experimental lean backend for Hax
-- The Hax prelude library can be found in hax/proof-libs/lean
import Hax
import Std.Tactic.Do
import Std.Do.Triple
import Std.Tactic.Do.Syntax
open Std.Do
open Std.Tactic
set_option mvcgen.warning false
set_option linter.unusedVariables false
";
impl RenderView for LeanPrinter {
fn reserved_keywords() -> &'static HashSet<String> {
static SET: OnceLock<HashSet<String>> = OnceLock::new();
SET.get_or_init(|| {
[
// reserved for Lean:
"end",
"def",
"abbrev",
"theorem",
"example",
"inductive",
"structure",
"from",
// reserved for hax encoding:
"associatedTypes",
"AssociatedTypes",
]
.into_iter()
.map(|s| s.to_string())
.collect()
})
}
fn should_escape(id: &str) -> bool {
Self::is_reserved_keyword(id)
|| id.starts_with(|c: char| c.is_ascii_digit())
|| id.starts_with("trait_constr_")
}
fn separator(&self) -> &str {
"."
}
fn relativize_module_path<'a>(&self, module_path: &'a [PathSegment]) -> &'a [PathSegment] {
if let Some(namespace) = self.current_namespace
&& namespace.view().segments() == module_path
{
&[]
} else {
module_path
}
}
fn render_path_segment(&self, chunk: &PathSegment) -> Vec<String> {
// Returning None indicates that the default rendering should be used
(match chunk.kind() {
AnyKind::Constructor(ConstructorKind::Constructor { ty })
if matches!(ty.kind(), TypeDefKind::Struct) =>
{
Some(vec![
Self::escape(&self.render_path_segment_payload(chunk.payload())),
"mk".to_string(),
])
}
AnyKind::Field { named: _, parent } => match parent.kind() {
ConstructorKind::Constructor { ty }
if matches!(&ty.kind(), TypeDefKind::Struct) =>
{
chunk.parent().map(|parent| {
vec![
Self::escape(&self.render_path_segment_payload(parent.payload())),
Self::escape(&self.render_path_segment_payload(chunk.payload())),
]
})
}
_ => None,
},
_ => None,
})
.unwrap_or(default::render_path_segment(self, chunk))
}
}
impl Printer for LeanPrinter {}
/// The Lean backend
pub struct LeanBackend;
impl Backend for LeanBackend {
type Printer = LeanPrinter;
fn module_path(&self, module: &Module) -> Utf8PathBuf {
let krate = module.ident.krate();
Utf8PathBuf::from(krate).with_extension("lean")
}
fn phases(&self) -> Vec<PhaseKind> {
use crate::phase::{PhaseKind::*, legacy::LegacyOCamlPhase::*};
vec![
RejectRawOrMutPointer.into(),
RejectImplTypeMethod.into(),
RewriteLocalSelf.into(),
TransformHaxLibInline.into(),
Specialize.into(),
DropSizedTrait.into(),
SimplifyQuestionMarks.into(),
AndMutDefsite.into(),
ReconstructAsserts.into(),
ReconstructForLoops.into(),
ReconstructWhileLoops.into(),
DirectAndMut.into(),
RejectArbitraryLhs.into(),
DropBlocks.into(),
DropMatchGuards.into(),
DropReferences.into(),
TrivializeAssignLhs.into(),
HoistSideEffects.into(),
HoistDisjunctivePatterns.into(),
SimplifyMatchReturn.into(),
LocalMutation.into(),
RewriteControlFlow.into(),
DropReturnBreakContinue.into(),
FunctionalizeLoops.into(),
RejectQuestionMark.into(),
TraitsSpecs.into(),
SimplifyHoisting.into(),
NewtypeAsRefinement.into(),
ReorderFields.into(),
SortItems.into(),
FilterUnprintableItems,
ExplicitMonadic,
]
}
fn resugaring_phases() -> Vec<Box<dyn Resugaring>> {
vec![
Box::new(RecursiveFunctions),
Box::new(FunctionsToConstants),
Box::new(LetPure),
Box::new(RecordEllipsis),
]
}
fn items_to_module(&self, items: Vec<Item>) -> Vec<Module> {
let mut modules: Vec<Module> = Vec::new();
for item in items {
let module_ident = item.ident.mod_only_closest_parent();
if let Some(last_module) = modules.last_mut()
&& last_module.ident == module_ident
{
last_module.items.push(item);
} else {
modules.push(Module {
ident: module_ident,
items: vec![item],
meta: Metadata {
span: Span::dummy(),
attributes: vec![],
},
});
}
}
modules
}
fn modules_to_files(&self, modules: Vec<Module>, mut printer: Self::Printer) -> Vec<File> {
if modules.is_empty() {
return vec![];
}
let path = self.module_path(modules.first().unwrap()).to_string();
let contents = modules
.into_iter()
.map(|module: Module| {
let (c, _) = printer.print(module);
c
})
.collect::<Vec<String>>()
.join("\n");
vec![File {
path,
contents: format!("{}{}", HEADER, contents),
sourcemap: None,
}]
}
}
impl LeanPrinter {
/// Checks if we are extracting core models to be able to use different namespeacing when
/// referring to core.
pub fn is_hax_core_models_extraction_mode(&self) -> bool {
std::env::var("HAX_CORE_MODELS_EXTRACTION_MODE")
.map(|v| v == "on")
.unwrap_or(false)
}
/// Returns whether `id` is an associated item of the trait whose
/// declaration is currently being emitted, i.e. whether `id` is a
/// sibling field of the surrounding `class ... where` block. Used to
/// detect intra-trait calls (`Self::F` from inside `trait Foo { ... }`)
/// so that the App printer can drop the trait qualification and the
/// explicit `Self` argument; Lean class elaboration resolves sibling
/// field names within the same `where` block via the implicit instance
/// being built. Note that hax view encoding combines a trait and its
/// associated item into a single path segment (e.g. `Foo::F`), so the
/// comparison is between the parent of `id`'s last segment and the last
/// segment of `current_trait`.
pub fn is_member_of_current_trait(&self, id: &GlobalId) -> bool {
self.current_trait.is_some_and(|trait_id| {
let id_view = id.view();
let trait_view = trait_id.view();
id_view
.last()
.parent()
.is_some_and(|parent| trait_view.last() == &parent)
})
}
/// Render a global id using the Rendering strategy of the Lean printer. Works for both concrete
/// and projector ids. TODO: https://github.com/cryspen/hax/issues/1660
pub fn render_id(&self, id: &GlobalId) -> String {
let id = if !self.is_hax_core_models_extraction_mode() && id.krate() == "core" {
id.rename_krate("core_models")
} else {
*id
};
self.render_string(&id.view())
}
/// Renders the last, most local part of an id. Used for named arguments of constructors.
pub fn render_last(&self, id: &GlobalId) -> String {
self.render(&id.view())
.path
.last()
// TODO: Should be ensured by the rendering engine; see
// https://github.com/cryspen/hax/issues/1660
.expect("Segments should always be non-empty")
.clone()
}
/// Inject an identifier in before-last position while rendering
/// TODO: use `DefIdInner::kind` for this instead (https://github.com/cryspen/hax/issues/1877)
pub fn render_with_injection(&self, id: &GlobalId, injection: &String) -> String {
let rendered = self.render(&id.view());
let (last, butlast) = rendered
.path
.split_last()
// TODO: Should be ensured by the rendering engine; see
// https://github.com/cryspen/hax/issues/1660
.expect("Segments should always be non-empty");
let path: Vec<String> = butlast
.iter()
.chain(std::iter::once(injection))
.chain(std::iter::once(last))
.map(String::clone)
.collect();
self.rendered_to_string(Rendered {
module: rendered.module,
path,
})
}
/// Escape a string for use in Lean string literals.
/// Handles newlines, quotes, backslashes, and other special characters.
fn escape_string(&self, s: &str) -> String {
let mut result = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' => result.push_str("\\\""),
'\'' => result.push_str("\\'"),
'\\' => result.push_str("\\\\"),
'\n' => result.push_str("\\n"),
'\r' => result.push_str("\\r"),
'\t' => result.push_str("\\t"),
c if c.is_ascii_control() => {
result.push_str(&format!("\\x{:02x}", c as u8));
}
c => result.push(c),
}
}
result
}
}
/// Render parameters, adding a line after each parameter
impl<A: 'static + Clone> ToDocument<LeanPrinter, A> for Vec<Param> {
fn to_document(&self, printer: &LeanPrinter) -> DocBuilder<A> {
printer.params(self)
}
}
#[prepend_associated_functions_with(install_pretty_helpers!(self: Self))]
const _: () = {
// Emits a CLI error with a github issue number, and prints "sorry" in the lean output
macro_rules! emit_error {($($tt:tt)*) => {disambiguated_todo!($($tt)*)};}
// Insert a new line in a doc (pretty)
macro_rules! line {($($tt:tt)*) => {disambiguated_line!($($tt)*)};}
// Concatenate docs (pretty )
macro_rules! concat {($($tt:tt)*) => {disambiguated_concat!($($tt)*)};}
// Given an iterable `[A,B, ... , C]` and a separator `S`, create the doc `ASBS...CS`
macro_rules! zip_right {
($a:expr, $sep:expr) => {
docs![concat!($a.into_iter().map(|a| docs![a, $sep]))]
};
}
// Given an iterable `[A,B, ... , C]` and a separator `S`, create the doc `SASB...SC`
macro_rules! zip_left {
($sep:expr, $a:expr) => {
docs![concat!($a.into_iter().map(|a| docs![$sep, a]))]
};
}
// Prints a one-line comment
macro_rules! comment {
($e:expr) => {
docs!["-- ", $e]
};
}
// Extra methods, specific to the LeanPrinter
impl LeanPrinter {
/// Prints arguments a variant or constructor of struct, using named or unamed arguments based
/// on the `is_record` flag. Used for both expressions and patterns
pub fn arguments<A: 'static + Clone, D>(
&self,
fields: &[(GlobalId, D)],
is_record: &bool,
) -> DocBuilder<A>
where
D: ToDocument<Self, A>,
{
if *is_record {
self.named_arguments(fields)
} else {
self.positional_arguments(fields)
}
}
/// Prints fields of structures (when in braced notation)
fn struct_fields<A: 'static + Clone, D>(&self, fields: &[(GlobalId, D)]) -> DocBuilder<A>
where
D: ToDocument<Self, A>,
{
docs![intersperse!(
fields
.iter()
.map(|(id, e)| { docs![self.render_last(id), reflow!(" := "), e].group() }),
docs![",", line!()]
)]
.group()
}
/// Prints named arguments (record) of a variant or constructor of struct
fn named_arguments<A: 'static + Clone, D>(&self, fields: &[(GlobalId, D)]) -> DocBuilder<A>
where
D: ToDocument<Self, A>,
{
docs![zip_left!(
line!(),
fields.iter().map(|(id, e)| {
docs![self.render_last(id), reflow!(" := "), e]
.parens()
.group()
})
)]
.group()
}
/// Prints positional arguments (tuple) of a variant or constructor of struct
fn positional_arguments<A: 'static + Clone, D>(
&self,
fields: &[(GlobalId, D)],
) -> DocBuilder<A>
where
D: ToDocument<Self, A>,
{
docs![zip_left!(line!(), fields.iter().map(|(_, e)| e))].group()
}
/// Prints parameters of functions (items, trait items, impl items)
fn params<A: 'static + Clone>(&self, params: &Vec<Param>) -> DocBuilder<A> {
zip_left!(line!(), params)
}
/// Print parameters as function arguments
fn params_as_args<A: 'static + Clone>(&self, params: &[Param]) -> DocBuilder<A> {
zip_left!(
line!(),
params.iter().map(|param| {
let Ty(ty_kind) = ¶m.ty;
// We need to print arguments of type `Tuple0` as `⟨⟩` instead of `_`
// https://github.com/cryspen/hax/issues/1856
if let TyKind::App { head, .. } = **ty_kind
&& let Some(global_id::TupleId::Type { length: 0 }) = head.expect_tuple()
{
docs!["⟨⟩"]
} else {
docs![param]
}
})
)
}
/// Renders expressions with an explicit ascription `(e : RustM ty)`. Used for the body of closure, for
/// numeric literals, etc.
fn expr_typed_result<A: 'static + Clone>(&self, expr: &Expr) -> DocBuilder<A> {
docs![
expr,
softline!(),
":",
line!(),
docs!["RustM", line!(), &expr.ty].group()
]
.group()
}
fn pat_typed<A: 'static + Clone>(&self, pat: &Pat) -> DocBuilder<A> {
docs![pat, reflow!(" :"), line!(), &pat.ty].parens().group()
}
fn do_block<A: 'static + Clone, D: ToDocument<Self, A>>(&self, body: D) -> DocBuilder<A> {
docs!["do", line!(), body].group()
}
/// Produces a name for a constraint on an trait-level constraint, or an associated
/// type. The name is obtained by combining the type it applies to and the name of the
/// constraint (and should be unique)
fn constraint_name(&self, type_name: &String, constraint: &ImplIdent) -> String {
format!("trait_constr_{}_{}", type_name, constraint.name)
}
/// Renders a named argument for associated types with equality constraints
/// (aka projections). If there are no equality constraints, returns None.
fn associated_type_projections<A: 'static + Clone>(
&self,
impl_ident: &ImplIdent,
projections: Vec<DocBuilder<A>>,
) -> Option<DocBuilder<A>> {
(!projections.is_empty()).then_some(
docs![
"(associatedTypes := {",
line!(),
docs![
"show",
line!(),
impl_ident.goal.trait_,
".AssociatedTypes",
zip_left!(line!(), impl_ident.goal.args.iter()),
]
.group()
.nest(INDENT),
line!(),
reflow!("by infer_instance"),
line!(),
docs![
"with",
line!(),
intersperse!(projections, docs![",", line!()]),
]
.group()
.nest(INDENT),
"})"
]
.group()
.nest(INDENT),
)
}
/// Turns an expression of type `RustM T` into one of type `T` (out of the monad), providing
/// reflexivity as a proof witness.
fn monad_extract<A: 'static + Clone>(&self, expr: &Expr) -> DocBuilder<A> {
if let ExprKind::App { head, args, .. } = expr.kind()
&& let ExprKind::GlobalId(PURE) = head.kind()
&& let [pure_expr] = &args[..]
&& let ExprKind::Literal(_) | ExprKind::GlobalId(_) | ExprKind::LocalId(_) =
pure_expr.kind()
{
// Pure values are displayed directly. Note that constructors, while pure, may
// contain sub-expressions that are not, so they must be wrapped in a do-block
docs![pure_expr]
} else {
// All other expressions are wrapped in a do-block, and extracted out of the monad
docs![
"RustM.of_isOk",
line!(),
self.do_block(expr).parens(),
line!(),
"(by rfl)"
]
.group()
.nest(INDENT)
}
}
/// Print trait items, adding trait-level params as extra arguments
fn trait_item_with_trait_params<A: 'static + Clone>(
&self,
trait_generics: &[GenericParam],
TraitItem {
meta: _,
kind,
generics: item_generics,
ident,
}: &TraitItem,
) -> DocBuilder<A> {
{
let name = self.render_last(ident);
let trait_generics = zip_left!(
softline!(),
trait_generics
.iter()
.map(|GenericParam { ident, .. }| docs![ident].parens())
);
docs![match kind {
TraitItemKind::Fn(ty) => {
docs![
name,
trait_generics,
self.generics(item_generics, &self.render_last(ident)),
softline!(),
":",
line!(),
ty
]
.group()
.nest(INDENT)
}
TraitItemKind::Type(_) => {
docs![name, softline!(), ":", line!(), "Type"]
.group()
.nest(INDENT)
}
TraitItemKind::Default { params, body } => docs![
docs![
name,
trait_generics,
self.generics(item_generics, &self.render_last(ident)),
zip_left!(line!(), params).group(),
softline!(),
":",
if params.is_empty() {
docs![body.ty, softline!(), reflow!(":=")]
} else {
docs!["RustM", softline!(), body.ty, softline!(), reflow!(":= do")]
.group()
}
]
.group(),
line!(),
if params.is_empty() {
self.monad_extract(body)
} else {
docs![body]
},
]
.group()
.nest(INDENT),
TraitItemKind::Resugared(_) => {
unreachable!("This backend has no resugaring for trait items")
}
TraitItemKind::Error(e) => docs![e],
}]
}
}
// Print generics, using `name` as a prefix for constraint names
fn generics<A: 'static + Clone>(
&self,
generics: &Generics,
name: &String,
) -> DocBuilder<A> {
docs![
zip_left!(line!(), &generics.params),
zip_left!(
line!(),
generics.type_class_constraints().map(|impl_ident| {
let projections = generics
.equality_constraints()
.filter(|p| !matches!(&*p.impl_.kind, ImplExprKind::LocalBound { id } if *id != impl_ident.name ))
.map(|p| {
if let ImplExprKind::LocalBound { .. } = &*p.impl_.kind {
docs![p]
} else if let ImplExprKind::Parent { .. } = &*p.impl_.kind {
emit_error!(issue 1923, "Unsupported equality constraints on associated types of parent trait")
} else {
emit_error!(issue 1924, "Unsupported variant of associated type projection")
}
})
.collect::<Vec<_>>();
docs![
docs![
self.constraint_name(&format!("{}_associated_type", name), impl_ident),
reflow!(" : "),
impl_ident.goal.trait_,
".AssociatedTypes",
concat!(
impl_ident.goal.args.iter().map(|arg| docs![line!(), arg])
)
]
.brackets()
.group()
.nest(INDENT),
line!(),
docs![
self.constraint_name(name, impl_ident),
reflow!(" : "),
impl_ident.goal.trait_,
concat!(
impl_ident.goal.args.iter().map(|arg| docs![line!(), arg])
),
line!(),
self.associated_type_projections(impl_ident, projections)
]
.brackets()
.nest(INDENT)
.group()
]
.group()
})
),
]
.group()
}
/// Print spec of an item
fn spec<A: 'static + Clone>(
&self,
item: &Item,
name: &GlobalId,
generics: &Generics,
params: &Vec<Param>,
) -> DocBuilder<A> {
let linked_items = HasLinkedItemGraph::linked_item_graph(self);
let spec = linked_items.fn_like_linked_expressions(item, item.self_id());
if !linked_items.has_spec(item) {
nil!()
} else {
match hax_proof_attributes(item) {
Err(message) => emit_error!("{message}"),
Ok(proof_attributes) => {
let (tactic, specset) = match proof_attributes.proof_method {
Some(ProofMethod::Grind) => ("grind", "int"),
Some(ProofMethod::BvDecide) | None => ("bv_decide", "bv"),
};
let pure_requires_proof = proof_attributes
.pure_requires_proof
.unwrap_or(format!("by hax_construct_pure <;> {tactic}"));
let pure_ensures_proof = proof_attributes
.pure_ensures_proof
.unwrap_or(format!("by hax_construct_pure <;> {tactic}"));
let proof = proof_attributes.proof.map(|s| docs![s]).unwrap_or(docs![
"by hax_mvcgen [",
name,
"] <;> ",
tactic
]);
{
docs![
hardline!(),
hardline!(),
docs!["set_option hax_mvcgen.specset \"", specset, "\" in"],
hardline!(),
"@[hax_spec]",
hardline!(),
docs![
docs![
"def",
line!(),
name,
".spec",
self.generics(generics, &self.render_last(name)),
params,
softline!(),
":"
]
.group()
.nest(INDENT),
line!(),
docs![
"Spec",
line!(),
docs![
"requires",
softline!(),
":= do",
line!(),
spec.precondition
.map_or(reflow!("pure True"), |p| docs![p])
]
.parens()
.group()
.nest(INDENT),
line!(),
docs![
"ensures := ",
spec.postcondition.map_or(
reflow!("fun _ => pure True"),
|p| docs![
"fun",
line!(),
p.result_binder,
softline!(),
"=> do",
line!(),
p.body,
]
.group()
.nest(INDENT)
),
]
.parens()
.group()
.nest(INDENT),
line!(),
docs![
name,
zip_left!(line!(), &generics.params),
self.params_as_args(params)
]
.parens()
.group()
.nest(INDENT)
]
.group()
.nest(INDENT),
softline!(),
":=",
]
.group()
.nest(2 * INDENT),
softline!(),
docs![
hardline!(),
docs!["pureRequires :=", softline!(), pure_requires_proof],
hardline!(),
docs!["pureEnsures :=", softline!(), pure_ensures_proof],
hardline!(),
docs!["contract :=", softline!(), proof]
.group()
.nest(INDENT),
hardline!(),
]
.nest(INDENT)
.braces(),
]
}
}
}
}
}
}
impl<A: 'static + Clone> ToDocument<LeanPrinter, A> for (Vec<GenericParam>, &TraitItem) {
fn to_document(&self, printer: &LeanPrinter) -> DocBuilder<A> {
printer.trait_item_with_trait_params(&self.0, self.1)
}
}
impl<A: 'static + Clone> PrettyAst<A> for LeanPrinter {
const NAME: &'static str = "Lean";
/// Produce a non-panicking placeholder document. In general, prefer the use of the helper macro [`todo_document!`].
fn todo_document(&self, message: &str, issue_id: Option<u32>) -> DocBuilder<A> {
<Self as PrettyAst<A>>::emit_diagnostic(
self,
hax_types::diagnostics::Kind::Unimplemented {
issue_id,
details: Some(message.into()),
},
);
text!("sorry")
}
fn module(&self, module: &Module) -> DocBuilder<A> {
let current_namespace = module.ident;
let new_printer = LeanPrinter {
current_namespace: Some(current_namespace),
..self.clone()
};
let items = &module.items;
docs![
"namespace ",
current_namespace,
hardline!(),
hardline!(),
intersperse!(
items.iter().map(|item| { item.to_document(&new_printer) }),
docs![hardline!(), hardline!()]
),
hardline!(),
hardline!(),
"end ",
current_namespace,
hardline!(),
hardline!(),
]
}
fn global_id(&self, global_id: &GlobalId) -> DocBuilder<A> {
docs![self.render_id(global_id)]
}
fn generics(&self, generics: &Generics) -> DocBuilder<A> {
self.generics(generics, &String::new())
}
fn generic_constraint(&self, _: &GenericConstraint) -> DocBuilder<A> {
unreachable!(
"Generic constraints are rendered inline because they must contain associated type projections."
)
}
fn generic_param(&self, generic_param: &GenericParam) -> DocBuilder<A> {
match generic_param.kind() {
GenericParamKind::Type => docs![&generic_param.ident, reflow!(" : Type")]
.parens()
.group(),
GenericParamKind::Lifetime => unreachable_by_invariant!(Drop_references),
GenericParamKind::Const { ty } => docs![&generic_param.ident, reflow!(" : "), ty]
.parens()
.group(),
}
}
fn generic_value(&self, generic_value: &GenericValue) -> DocBuilder<A> {
match generic_value {
GenericValue::Ty(ty) => docs![ty],
GenericValue::Expr(expr) => docs![expr].parens(),
GenericValue::Lifetime => unreachable_by_invariant!(Drop_references),
}
}
fn expr(&self, Expr { kind, ty, meta: _ }: &Expr) -> DocBuilder<A> {
match &**kind {
ExprKind::If {
condition,
then,
else_,
} => {
if let Some(else_branch) = else_ {
docs![
docs!["if", line!(), condition, reflow!(" then do")].group(),
docs![line!(), then].nest(INDENT),
line!(),
reflow!("else do"),
docs![line!(), else_branch].nest(INDENT)
]
.group()
} else {
unreachable_by_invariant!(Local_mutation)
}
}
ExprKind::App {
head,
args,
generic_args,
bounds_impls: _,
trait_,
} => {
match (&args[..], &generic_args[..], head.kind()) {
([arg], [], ExprKind::GlobalId(LIFT)) => docs![reflow!("← "), arg].parens(),
([arg], [], ExprKind::GlobalId(PURE)) => {
docs![reflow!("pure "), arg].parens()
}
([arg], [], ExprKind::GlobalId(CAST_OP)) => docs![
// Add type annotation for `cast_op`:
docs![head, line!(), arg],
softline!(),
":",
line!(),
"RustM",
softline!(),
ty
]
.parens()
.group()
.nest(INDENT),
// TODO: Replace this match pattern with an `if let` guard when the feature stabilizes
// Tracking PR: https://github.com/rust-lang/rust/pull/141295
(
[arg],
[],
ExprKind::GlobalId(op @ (binops::neg | binops::not | binops::Not::not)),
) if arg.ty == Ty::bool() || arg.ty.is_int() => {
let symbol = match *op {
binops::neg => "-?",
binops::not => "~?",
binops::Not::not => "!?",
_ => unreachable!(),
};
docs![symbol, softline!(), arg].parens()
}
([lhs, rhs], [], ExprKind::GlobalId(binops::Index::index)) => {
docs![lhs, "[", line_!(), rhs, line_!(), "]_?"]
.nest(INDENT)
.group()
}
// TODO: Replace this match pattern with an `if let` guard when the feature stabilizes
// Tracking PR: https://github.com/rust-lang/rust/pull/141295
(
[lhs, rhs],
[],
ExprKind::GlobalId(
op @ (binops::add
| binops::sub
| binops::mul
| binops::div
| binops::rem
| binops::shr
| binops::shl
| binops::bitand
| binops::BitAnd::bitand
| binops::bitor
| binops::BitOr::bitor
| binops::bitxor
| binops::BitXor::bitxor
| binops::logical_op_and
| binops::logical_op_or
| binops::eq
| binops::PartialEq::eq
| binops::lt
| binops::le
| binops::gt
| binops::ge
| binops::ne
| binops::PartialEq::ne),
),
) if (lhs.ty == Ty::bool() && rhs.ty == Ty::bool())
|| (rhs.ty.is_int() && lhs.ty.is_int()) =>
{
let symbol = match *op {
binops::add => "+?",
binops::sub => "-?",
binops::mul => "*?",