source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/proofwidgets/ProofWidgets/Component/Panel/GoalTypePanel.lean
module public meta import ProofWidgets.Component.Panel.Basic public meta section namespace ProofWidgets /-- Display the goal type using known `Expr` presenters. -/ @[widget_module] def GoalTypePanel : Component PanelWidgetProps where javascript := include_str ".." / ".." / ".." / ".lake" / "build" / "js" / "goalTypePanel.js" end ProofWidgets
.lake/packages/proofwidgets/ProofWidgets/Data/Svg.lean
module public meta import ProofWidgets.Data.Html public meta import Std.Data.HashMap public meta section namespace ProofWidgets open Lean Std private def _root_.Float.toInt (x : Float) : Int := if x >= 0 then x.toUInt64.toNat else -((-x).toUInt64.toNat) private def _root_.Int.toFloat (i : Int) : Float := if i >= 0 then i.toNat.toFloat else -((-i).toNat.toFloat) namespace Svg structure Frame where (xmin ymin : Float) (xSize : Float) (width height : Nat) deriving ToJson, FromJson def Frame.ySize (frame : Frame) : Float := frame.height.toFloat * (frame.xSize / frame.width.toFloat) def Frame.xmax (frame : Frame) : Float := frame.xmin + frame.xSize def Frame.ymax (frame : Frame) : Float := frame.ymin + frame.ySize def Frame.pixelSize (frame : Frame) : Float := frame.xSize / frame.width.toFloat structure Color where (r := 0.0) (g := 0.0) (b := 0.0) deriving ToJson, FromJson instance : Coe (Float×Float×Float) Color := ⟨λ (r,g,b) => ⟨r,g,b⟩⟩ /-- Returns string "rgb(r, g, b)" with `r,g,b ∈ [0,...,256)` -/ def Color.toStringRGB (c : Color) : String := s!"rgb({255*c.r}, {255*c.g}, {255*c.b})" inductive Point (f : Frame) where | px (i j : Int) | abs (x y : Float) deriving Inhabited, ToJson, FromJson instance (f) : Coe (Float×Float) (Point f) := ⟨λ (x,y) => .abs x y⟩ instance (f) : Coe (Int×Int) (Point f) := ⟨λ (i,j) => .px i j⟩ def Point.toPixels {f : Frame} (p : Point f) : Int × Int := match p with | .px x y => (x,y) | .abs x y => let Δx := f.pixelSize let i := ((x - f.xmin) / Δx).floor.toInt let j := ((f.ymax - y) / Δx).floor.toInt (i, j) def Point.toAbsolute {f : Frame} (p : Point f) : Float × Float := match p with | .abs x y => (x,y) | .px i j => let Δx := f.pixelSize let x := f.xmin + (i.toFloat + 0.5) * Δx let y := f.ymax - (j.toFloat + 0.5) * Δx (x,y) inductive Size (f : Frame) where | px (size : Nat) : Size f | abs (size : Float) : Size f deriving ToJson, FromJson def Size.toPixels {f : Frame} (s : Size f) : Nat := match s with | .px x => x | .abs x => (x / f.pixelSize).ceil.toUInt64.toNat -- inductive PolylineType inductive Shape (f : Frame) where | line (src trg : Point f) | circle (center : Point f) (radius : Size f) | polyline (points : Array (Point f)) -- (type : PolylineType) | polygon (points : Array (Point f)) | path (d : String) | ellipse (center : Point f) (rx ry : Size f) | rect (corner : Point f) (width height : Size f) | text (pos : Point f) (content : String) (size : Size f) deriving ToJson, FromJson def Shape.toHtmlData {f : Frame} : Shape f → String × Array (String × Json) | .line src trg => let (x1,y1) := src.toPixels let (x2,y2) := trg.toPixels ("line", #[("x1", x1), ("y1", y1), ("x2", x2), ("y2", y2)]) | .circle center radius => let (cx,cy) := center.toPixels let r := radius.toPixels ("circle", #[("cx", cx), ("cy", cy), ("r", r)]) | .polyline points => let pts := points |>.map (λ p => let (x,y) := p.toPixels; s!"{x},{y}") |>.foldl (init := "") (λ s p => s ++ " " ++ p) ("polyline", #[("points", pts)]) | .polygon points => let pts := points |>.map (λ p => let (x,y) := p.toPixels; s!"{x},{y}") |>.foldl (init := "") (λ s p => s ++ " " ++ p) ("polygon", #[("fillRule", "nonzero"), ("points", pts)]) | .path d => ("path", #[("d", d)]) | .ellipse center rx ry => let (cx,cy) := center.toPixels let rX := rx.toPixels let rY := ry.toPixels ("ellipse", #[("cx", cx), ("cy", cy), ("rx", rX), ("ry", rY)]) | .rect corner width height => let (x,y) := corner.toPixels let w := width.toPixels let h := height.toPixels ("rect", #[("x", x), ("y", y), ("width", w), ("height", h)]) | .text pos content size => let (x,y) := pos.toPixels let fontSize := size.toPixels ("text", #[("x", x), ("y", y), ("font-size", fontSize), ("text", content)]) structure Element (f : Frame) where shape : Shape f strokeColor := (none : Option Color) strokeWidth := (none : Option (Size f)) fillColor := (none : Option Color) id := (none : Option String) data := (none : Option Json) deriving ToJson, FromJson def Element.setStroke {f} (elem : Element f) (color : Color) (width : Size f) := { elem with strokeColor := some color, strokeWidth := some width } def Element.setFill {f} (elem : Element f) (color : Color) := { elem with fillColor := some color } def Element.setId {f} (elem : Element f) (id : String) := { elem with id := some id } def Element.setData {α : Type} {f} (elem : Element f) (a : α) [ToJson α] := { elem with data := some (toJson a) } def Element.toHtml {f : Frame} (e : Element f) : Html := Id.run do let mut (tag, args) := e.shape.toHtmlData let mut children := #[] if let .text _ content _ := e.shape then children := #[.text content] -- adding children <text> if let .some color := e.strokeColor then args := args.push ("stroke", color.toStringRGB) if let .some width := e.strokeWidth then args := args.push ("strokeWidth", width.toPixels) if let .some color := e.fillColor then args := args.push ("fill", color.toStringRGB) else args := args.push ("fill", "none") if let .some id := e.id then args := args.push ("id", id) if let .some data := e.data then args := args.push ("data", data) return .element tag args children def line {f} (p q : Point f) : Element f := { shape := .line p q } def circle {f} (c : Point f) (r : Size f) : Element f := { shape := .circle c r } def polyline {f} (pts : Array (Point f)) : Element f := { shape := .polyline pts } def polygon {f} (pts : Array (Point f)) : Element f := { shape := .polygon pts } def path {f} (d : String) : Element f := { shape := .path d } def ellipse {f} (center : Point f) (rx ry : Size f) : Element f := { shape := .ellipse center rx ry } def rect {f} (corner : Point f) (width height : Size f) : Element f := { shape := .rect corner width height } def text {f} (pos : Point f) (content : String) (size : Size f) : Element f := { shape := .text pos content size } end Svg def mkIdToIdx {f} (elements : Array (Svg.Element f)) : Std.HashMap String (Fin elements.size) := let idToIdx := elements |>.mapFinIdx (λ idx el h => (⟨idx, h⟩, el)) -- zip with `Fin` index |>.filterMap (λ (idx,el) => el.id.map (λ id => (id, idx))) -- keep only elements with specified id |>.toList |> Std.HashMap.ofList idToIdx structure Svg (f : Svg.Frame) where elements : Array (Svg.Element f) idToIdx := mkIdToIdx elements namespace Svg open scoped ProofWidgets.Jsx def toHtml {f : Frame} (svg : Svg f) : Html := <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width={f.width} height={f.height}> {... svg.elements.map (·.toHtml)} </svg> def idToDataList {f} (svg : Svg f) : List (String × Json) := svg.elements.foldr (init := []) (λ e l => match e.id, e.data with | some id, some data => (id,data)::l | _, _ => l) def idToData {f} (svg : Svg f) : Std.HashMap String Json := HashMap.ofList svg.idToDataList instance {f} : GetElem (Svg f) Nat (Svg.Element f) (λ svg idx => idx < svg.elements.size) where getElem svg i h := svg.elements[i] instance {f} : GetElem (Svg f) String (Option (Svg.Element f)) (λ _ _ => True) where getElem svg id _ := svg.idToIdx[id]?.map (λ idx => svg.elements[idx]) def getData {f} (svg : Svg f) (id : String) : Option Json := match svg[id] with | none => none | some elem => elem.data end Svg end ProofWidgets
.lake/packages/proofwidgets/ProofWidgets/Data/Html.lean
/- Copyright (c) 2021-2023 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Sebastian Ullrich, Eric Wieser -/ module public meta import Lean.Data.Json.FromToJson public meta import Lean.Parser public meta import Lean.PrettyPrinter.Delaborator.Basic public meta import Lean.Server.Rpc.Basic public meta import ProofWidgets.Component.Basic public meta import ProofWidgets.Util public meta section /-! We define a representation of HTML trees together with a JSX-like DSL for writing them. -/ namespace ProofWidgets open Lean Server ProofWidgets.Util /-- A HTML tree which may contain widget components. -/ inductive Html where /-- An `element "tag" attrs children` represents `<tag {...attrs}>{...children}</tag>`. -/ | element : String → Array (String × Json) → Array Html → Html /-- Raw HTML text. -/ | text : String → Html /-- A `component h e props children` represents `<Foo {...props}>{...children}</Foo>`, where `Foo : Component Props` is some component such that `h = hash Foo.javascript`, `e = Foo.«export»`, and `props` will produce a JSON-encoded value of type `Props`. -/ | component : UInt64 → String → LazyEncodable Json → Array Html → Html deriving Inhabited, RpcEncodable def Html.ofComponent [RpcEncodable Props] (c : Component Props) (props : Props) (children : Array Html) : Html := .component (hash c.javascript) c.export (rpcEncode props) children /-- See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout/Block_and_Inline_Layout_in_Normal_Flow). -/ inductive LayoutKind where | block | inline namespace Jsx open Parser PrettyPrinter declare_syntax_cat jsxElement declare_syntax_cat jsxChild declare_syntax_cat jsxAttr declare_syntax_cat jsxAttrVal scoped syntax str : jsxAttrVal /-- Interpolates an expression into a JSX attribute literal. -/ scoped syntax group("{" term "}") : jsxAttrVal scoped syntax ident "=" jsxAttrVal : jsxAttr /-- Interpolates a collection into a JSX attribute literal. For HTML tags, this should have type `Array (String × Json)`. For `ProofWidgets.Component`s, it can be any structure `$t` whatsoever: it is interpolated into the component's props using `{ $t with ... }` notation. -/ scoped syntax group(" {..." term "}") : jsxAttr /-- Characters not allowed inside JSX plain text. -/ def jsxTextForbidden : String := "{<>}$" /-- A plain text literal for JSX (notation for `Html.text`). -/ def jsxText : Parser := withAntiquot (mkAntiquot "jsxText" `ProofWidgets.Jsx.jsxText) { fn := fun c s => let startPos := s.pos let s := takeWhile1Fn (not ∘ jsxTextForbidden.contains) "expected JSX text" c s mkNodeToken `ProofWidgets.Jsx.jsxText startPos true c s } def getJsxText : TSyntax ``jsxText → String | stx => stx.raw[0].getAtomVal @[combinator_formatter ProofWidgets.Jsx.jsxText] def jsxText.formatter : Formatter := Formatter.visitAtom ``jsxText @[combinator_parenthesizer ProofWidgets.Jsx.jsxText] def jsxText.parenthesizer : Parenthesizer := Parenthesizer.visitToken scoped syntax "<" ident jsxAttr* "/>" : jsxElement scoped syntax "<" ident jsxAttr* ">" jsxChild* "</" ident ">" : jsxElement scoped syntax jsxText : jsxChild /-- Interpolates an array of elements into a JSX literal -/ scoped syntax "{..." term "}" : jsxChild /-- Interpolates an expression into a JSX literal -/ scoped syntax "{" term "}" : jsxChild scoped syntax jsxElement : jsxChild scoped syntax:max jsxElement : term def transformTag (tk : Syntax) (n m : Ident) (vs : Array (TSyntax `jsxAttr)) (cs : Array (TSyntax `jsxChild)) : MacroM Term := do let nId := n.getId.eraseMacroScopes let mId := m.getId.eraseMacroScopes if nId != mId then Macro.throwErrorAt m s!"expected </{nId}>" let trailingWs (stx : Syntax) := if let .original _ _ trailing _ := stx.getTailInfo then trailing.toString else "" -- Whitespace appearing before the current child. let mut wsBefore := trailingWs tk -- This loop transforms (for example) `` `(jsxChild*| {a} text {...cs} {d})`` -- into ``children ← `(term| #[a, Html.text " text "] ++ cs ++ #[d])``. let mut csArrs := #[] let mut csArr := #[] for c in cs do match c with | `(jsxChild| $t:jsxText) => csArr ← csArr.push <$> `(Html.text $(quote <| wsBefore ++ getJsxText t)) wsBefore := "" | `(jsxChild| { $t }%$tk) => csArr := csArr.push t wsBefore := trailingWs tk | `(jsxChild| $e:jsxElement) => csArr ← csArr.push <$> `(term| $e:jsxElement) wsBefore := trailingWs e | `(jsxChild| {... $t }%$tk) => if !csArr.isEmpty then csArrs ← csArrs.push <$> `(term| #[$csArr,*]) csArr := #[] csArrs := csArrs.push t wsBefore := trailingWs tk | stx => Macro.throwErrorAt stx "unknown syntax" if !csArr.isEmpty then csArrs ← csArrs.push <$> `(term| #[$csArr,*]) let children ← joinArrays csArrs let vs : Array ((Ident × Term) ⊕ Term) ← vs.mapM fun | `(jsxAttr| $attr:ident = $s:str) => Sum.inl <$> pure (attr, s) | `(jsxAttr| $attr:ident = { $t:term }) => Sum.inl <$> pure (attr, t) | `(jsxAttr| {... $t:term }) => Sum.inr <$> pure t | stx => Macro.throwErrorAt stx "unknown syntax" let tag := toString nId -- Uppercase tags are parsed as components if String.Pos.Raw.get? tag 0 |>.filter (·.isUpper) |>.isSome then let withs : Array Term ← vs.filterMapM fun | .inr e => return some e | .inl _ => return none let vs ← vs.filterMapM fun | .inl (attr, val) => return some <| ← `(Term.structInstField| $attr:ident := $val) | .inr _ => return none let props ← match withs, vs with | #[w], #[] => pure w | _, _ => `({ $withs,* with $vs:structInstField,* }) `(Html.ofComponent $n $props $children) -- Lowercase tags are parsed as standard HTML else let vs ← joinArrays <| ← foldInlsM vs (fun vs' => do let vs' ← vs'.mapM (fun (k, v) => `(term| ($(quote <| toString k.getId), ($v : Json)))) `(term| #[$vs',*])) `(Html.element $(quote tag) $vs $children) /-- Support for writing HTML trees directly, using XML-like angle bracket syntax. It works very similarly to [JSX](https://react.dev/learn/writing-markup-with-jsx) in JavaScript. The syntax is enabled using `open scoped ProofWidgets.Jsx`. Lowercase tags are interpreted as standard HTML whereas uppercase ones are expected to be `ProofWidgets.Component`s. -/ macro_rules | `(<$n:ident $[$attrs:jsxAttr]* />%$tk) => transformTag tk n n attrs #[] | `(<$n:ident $[$attrs:jsxAttr]* >%$tk $cs*</$m>) => transformTag tk n m attrs cs section delaborator open Lean Delaborator SubExpr /-! First delaborate into our non-term `TSyntax`. Note this means we can't call `delab`, so we have to add the term annotations ourselves. -/ partial def delabHtmlText : DelabM (TSyntax ``jsxText) := do let_expr Html.text e := ← getExpr | failure let .lit (.strVal s) := e | failure if s.any jsxTextForbidden.contains then failure annotateTermLikeInfo <| mkNode ``jsxText #[mkAtom s] mutual partial def delabHtmlElement' : DelabM (TSyntax `jsxElement) := do let_expr Html.element tag _attrs _children := ← getExpr | failure let .lit (.strVal s) := tag | failure let tag ← withNaryArg 0 <| annotateTermLikeInfo <| mkIdent <| .mkSimple s let attrs ← withNaryArg 1 <| try delabArrayLiteral <| withAnnotateTermLikeInfo do let_expr Prod.mk _ _ a _ := ← getExpr | failure let .lit (.strVal a) := a | failure let attr ← withNaryArg 2 <| annotateTermLikeInfo <| mkIdent <| .mkSimple a withNaryArg 3 do let v ← getExpr -- If the attribute's value is a string literal, -- use `attr="val"` syntax. -- TODO: also do this for `.ofComponent`. -- WN: not sure if matching a string literal is possible with `let_expr`. match v with | .app (.const ``Json.str _) (.lit (.strVal v)) => -- TODO: this annotation doesn't seem to work in infoview let val ← annotateTermLikeInfo <| Syntax.mkStrLit v `(jsxAttr| $attr:ident=$val:str) | _ => let val ← delab `(jsxAttr| $attr:ident={ $val }) catch _ => let vs ← delab return #[← `(jsxAttr| {... $vs })] let children ← withAppArg delabJsxChildren if children.isEmpty then `(jsxElement| < $tag $[$attrs]* />) else `(jsxElement| < $tag $[$attrs]* > $[$children]* </ $tag >) partial def delabHtmlOfComponent' : DelabM (TSyntax `jsxElement) := do let_expr Html.ofComponent _Props _inst _c _props _children := ← getExpr | failure let c ← withNaryArg 2 delab unless c.raw.isIdent do failure let tag : Ident := ⟨c.raw⟩ -- TODO: handle `Props` that do not delaborate to `{ }`, such as `Prod`, by parsing the `Expr` -- instead. let attrDelab ← withNaryArg 3 delab let attrs : Array (TSyntax `jsxAttr) ← do let `(term| { $[$ns:ident := $vs],* } ) := attrDelab | pure #[← `(jsxAttr| {...$attrDelab})] ns.zip vs |>.mapM fun (n, v) => do `(jsxAttr| $n:ident={ $v }) let children ← withNaryArg 4 delabJsxChildren if children.isEmpty then `(jsxElement| < $tag $[$attrs]* />) else `(jsxElement| < $tag $[$attrs]* > $[$children]* </ $tag >) partial def delabJsxChildren : DelabM (Array (TSyntax `jsxChild)) := do try delabArrayLiteral (withAnnotateTermLikeInfo do try match_expr ← getExpr with | Html.text _ => let html ← delabHtmlText return ← `(jsxChild| $html:jsxText) | Html.element _ _ _ => let html ← delabHtmlElement' return ← `(jsxChild| $html:jsxElement) | Html.ofComponent _ _ _ _ _ => let comp ← delabHtmlOfComponent' return ← `(jsxChild| $comp:jsxElement) | _ => failure catch _ => let fallback ← delab return ← `(jsxChild| { $fallback })) catch _ => let vs ← delab return #[← `(jsxChild| {... $vs })] end /-! Now wrap our `TSyntax _` delaborators into `Term` elaborators. -/ @[delab app.ProofWidgets.Html.element] def delabHtmlElement : Delab := do let t ← delabHtmlElement' `(term| $t:jsxElement) @[delab app.ProofWidgets.Html.ofComponent] def delabHtmlOfComponent : Delab := do let t ← delabHtmlOfComponent' `(term| $t:jsxElement) end delaborator end Jsx end ProofWidgets
.lake/packages/proofwidgets/ProofWidgets/Demos/Svg.lean
module public meta import ProofWidgets.Data.Svg public meta import ProofWidgets.Component.HtmlDisplay public meta section open ProofWidgets Svg private def frame : Frame where xmin := 0 ymin := 0 xSize := 450 width := 450 height := 450 private def github : Svg frame := { elements := #[ circle (200.0, 245.0) (.px 175) |>.setFill (1.0, 1.0, 1.0), path "M195,25C99.3,25,20,104.3,20,200C20,276,70.4,340.9,140.8,370.2C151.9,372.2,155.4,365.4,155.4,359.4C155.4,354,155.2,338.7,155.1,320C104.7,332.6,92.9,296.4,92.9,296.4C83.9,270.7,70.5,263.9,70.5,263.9C53.4,250.3,71.8,250.5,71.8,250.5C90.8,251.8,101.2,272.8,101.2,272.8C118.1,305.3,146.8,297.2,155.8,291.4C157.7,277.2,162.7,267.4,168.2,261.9C128.5,256.3,86.7,237.4,86.7,170.8C86.7,148.4,94.3,130.2,101.6,116.2C99.4,110.5,92.7,85.9,103.9,56.8C103.9,56.8,119.7,49.7,154.7,73.9C169.4,68.3,185.2,65.4,200.9,65.2C216.6,65.4,232.5,68.3,247.2,73.9C282.1,49.7,297.9,56.8,297.9,56.8C309.1,85.9,302.4,110.5,300.2,116.2C307.5,130.2,315.1,148.4,315.1,170.8C315.1,237.6,273.2,256.2,233.3,261.7C240.4,268.5,246.7,282,246.7,302.5C246.7,332.5,246.4,352.2,246.4,359.4C246.4,365.5,249.8,372.3,261.2,370.1C331.4,340.8,381.7,276,381.7,200C381.7,104.3,302.4,25,206.7,25L195,25Z" |>.setFill (0.2, 0.2, 0.2), circle (160.0, 245.0) (.px 15) |>.setFill (0.2, 0.2, 0.2), circle (240.0, 245.0) (.px 15) |>.setFill (0.2, 0.2, 0.2), text (150.0, 340.0) "GitHub" (.px 36) |>.setFill (0.8, 0.8, 0.8) ] } #html github.toHtml private def triangle01 : Svg frame := {elements := #[ path "M 100 100 L 300 100 L 200 300 z" |>.setFill ( 1.0 , 0. , 0.) |>.setStroke (136., 136., 136.) (.px 3) ]} #html triangle01.toHtml private def cubic01 : Svg frame := { elements := #[ polyline #[ (100.,200.), (100.,100.)] |>.setStroke (136., 136., 136.) (.px 2), polyline #[ (250.,100.), (250.,200.)] |>.setStroke (136., 136., 136.) (.px 2), polyline #[ (250.,200.), (250.,300.)] |>.setStroke (136., 136., 136.) (.px 2), polyline #[ (400.,300.), (400.,200.)] |>.setStroke (136., 136., 136.) (.px 2), path "M100,250 C100,350 250,350 250,250 S400,150 400,250" |>.setStroke (136., 136., 136.) (.px 2), circle (100.0, 200.0) (.px 10) |>.setStroke (136., 136., 136.) (.px 2), circle (250.0, 200.0) (.px 10) |>.setStroke (136., 136., 136.) (.px 2), circle (400.0, 200.0) (.px 10) |>.setStroke (136., 136., 136.) (.px 2), circle (100.0, 100.0) (.px 10) |>.setFill (0.8, 0.8, 0.8), circle (250.0, 100.0) (.px 10) |>.setFill (0.8, 0.8, 0.8), circle (400.0, 300.0) (.px 10) |>.setFill (0.8, 0.8, 0.8), circle (250.0, 300.0) (.px 9) |>.setStroke (0., 0., 1.) (.px 4) ] } #html cubic01.toHtml private def svgprims : Svg frame := {elements := #[ rect (100.0, 100.0) (.abs 70.0) (.abs 70.0) |>.setStroke (255., 0., 0.) (.px 2) |>.setFill (0.5, 0.5, 0.5), ellipse (200.0, 200.0) (.abs 50.0) (.abs 30.0) |>.setStroke (0., 255., 0.) (.px 2) |>.setFill (0.3, 0.3, 1.0), line (300.0, 300.0) (350.0, 350.0) |>.setStroke (255., 255., 0.) (.px 2), polygon #[ (100., 50.), (50., 150.), (150., 150.), (20.,70.) ] |>.setStroke (0., 0., 255.) (.px 2) |>.setFill (0., 1., 0.) ] } #html svgprims.toHtml
.lake/packages/proofwidgets/ProofWidgets/Demos/Dynkin.lean
module public meta import ProofWidgets.Component.HtmlDisplay public meta section /-! Ported from Lean 3 code by Oliver Nash: https://gist.github.com/ocfnash/fb61a17d0f1598edcc752999f17b70c6 -/ def List.product : List α → List β → List (α × β) | [], _ => [] | a::as, bs => bs.map ((a, ·)) ++ as.product bs @[expose] def Matrix (n m α : Type) := n → m → α namespace Matrix open ProofWidgets open scoped Jsx variable {n : Nat} (A : Matrix (Fin n) (Fin n) Int) def nat_index (i j : Nat) : Int := if h : i < n ∧ j < n then A ⟨i, h.1⟩ ⟨j, h.2⟩ else 999 /-- TODO Delete me once `get_node_pos` smart enough to infer layout from values in `A`. -/ def get_node_pos_E : Nat → Nat × Nat | 0 => ⟨0, 0⟩ | 1 => ⟨2, 1⟩ | (i+1) => ⟨i, 0⟩ /-- TODO Use `A` to infer sensible layout. -/ def get_node_pos (n : Nat) : Nat → Nat × Nat := if n < 6 then ((·, 0)) else get_node_pos_E def get_node_cx (n i : Nat) : Int := 20 + (get_node_pos n i).1 * 40 def get_node_cy (n i : Nat) : Int := 20 + (get_node_pos n i).2 * 40 def get_node_html (n i : Nat) : Html := <circle cx={toString <| get_node_cx n i} cy={toString <| get_node_cy n i} r="10" fill="white" stroke="black" /> /-- TODO * Error if `j ≤ i` * Error if `(A i j, A j i) ∉ [((0 : Int), (0 : Int)), (-1, -1), (-1, -2), (-2, -1), (-1, -3), (-3, -1)]` * Render `(A i j) * (A j i)` edges * Render arrow on double or triple edge with direction decided by `A i j < A j i` -/ def get_edge_html : Nat × Nat → List Html | (i, j) => if A.nat_index i j = 0 then [] else [<line x1={toString <| get_node_cx n i} y1={toString <| get_node_cy n i} x2={toString <| get_node_cx n j} y2={toString <| get_node_cy n j} fill="black" stroke="black" />] def get_nodes_html (n : Nat) : List Html := (List.range n).map (get_node_html n) def get_edges_html : List Html := Id.run do let mut out := [] for j in [:n] do for i in [:j] do out := A.get_edge_html (i, j) ++ out return out def toHtml (M : Matrix (Fin n) (Fin n) Int) : Html := <div style={json% { height: "100px", width: "300px", background: "grey" }}> {Html.element "svg" #[] (M.get_edges_html ++ Matrix.get_nodes_html n).toArray} </div> end Matrix def cartanMatrix.E₈ : Matrix (Fin 8) (Fin 8) Int := fun i j => [[ 2, 0, -1, 0, 0, 0, 0, 0], [ 0, 2, 0, -1, 0, 0, 0, 0], [-1, 0, 2, -1, 0, 0, 0, 0], [ 0, -1, -1, 2, -1, 0, 0, 0], [ 0, 0, 0, -1, 2, -1, 0, 0], [ 0, 0, 0, 0, -1, 2, -1, 0], [ 0, 0, 0, 0, 0, -1, 2, -1], [ 0, 0, 0, 0, 0, 0, -1, 2]][i]![j]! -- Place your cursor here #html cartanMatrix.E₈.toHtml
.lake/packages/proofwidgets/ProofWidgets/Demos/Euclidean.lean
/- Copyright (c) 2023 Vladimir Sedlacek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Vladimir Sedlacek, Wojciech Nawrocki -/ module public meta import Lean.Elab.Tactic public meta import ProofWidgets.Component.PenroseDiagram public meta import ProofWidgets.Component.HtmlDisplay public meta import ProofWidgets.Component.Panel.Basic public meta import ProofWidgets.Component.OfRpcMethod public meta import ProofWidgets.Component.MakeEditLink public meta section /-! A widget to display Euclidean geometry diagrams, and another one to make geometric constructions in the UI. -/ open Lean Meta Server open ProofWidgets Penrose /-! # Minimal definitions of synthetic geometric primitives Inspired by https://github.com/ah1112/synthetic_euclid_4. -/ class IncidenceGeometry where Point : Type u₁ Line : Type u₂ Circle : Type u₃ between : Point → Point → Point → Prop -- implies colinearity onLine : Point → Line → Prop onCircle : Point → Circle → Prop inCircle : Point → Circle → Prop centerCircle : Point → Circle → Prop circlesInter : Circle → Circle → Prop ne_23_of_between : ∀ {a b c : Point}, between a b c → b ≠ c line_unique_of_pts : ∀ {a b : Point}, ∀ {L M : Line}, a ≠ b → onLine a L → onLine b L → onLine a M → onLine b M → L = M onLine_2_of_between : ∀ {a b c : Point}, ∀ {L : Line}, between a b c → onLine a L → onLine c L → onLine b L line_of_pts : ∀ a b, ∃ L, onLine a L ∧ onLine b L circle_of_ne : ∀ a b, a ≠ b → ∃ C, centerCircle a C ∧ onCircle b C circlesInter_of_onCircle_inCircle : ∀ {a b α β}, onCircle b α → onCircle a β → inCircle a α → inCircle b β → circlesInter α β pts_of_circlesInter : ∀ {α β}, circlesInter α β → ∃ a b, a ≠ b ∧ onCircle a α ∧ onCircle a β ∧ onCircle b α ∧ onCircle b β inCircle_of_centerCircle : ∀ {a α}, centerCircle a α → inCircle a α open IncidenceGeometry /-! # Metaprogramming utilities to break down expressions -/ /-- If `e == between a b c` return `some (a, b, c)`, otherwise `none`. -/ def isBetweenPred? (e : Expr) : Option (Expr × Expr × Expr) := do let some (_, a, b, c) := e.app4? ``between | none return (a, b, c) /-- If `e == onLine a L` return `some (a, L)`, otherwise `none`. -/ def isOnLinePred? (e : Expr) : Option (Expr × Expr) := do let some (_, a, L) := e.app3? ``onLine | none return (a, L) /-- If `e == onCircle a C` return `some (a, C)`, otherwise `none`. -/ def isOnCirclePred? (e : Expr) : Option (Expr × Expr) := do let some (_, a, C) := e.app3? ``onCircle | none return (a, C) /-- If `e == inCircle a C` return `some (a, C)`, otherwise `none`. -/ def isInCirclePred? (e : Expr) : Option (Expr × Expr) := do let some (_, a, C) := e.app3? ``inCircle | none return (a, C) /-- If `e == centerCircle a C` return `some (a, C)`, otherwise `none`. -/ def isCenterCirclePred? (e : Expr) : Option (Expr × Expr) := do let some (_, a, C) := e.app3? ``centerCircle | none return (a, C) /-- If `e == circlesInter a C` return `some (a, C)`, otherwise `none`. -/ def isCirclesInterPred? (e : Expr) : Option (Expr × Expr) := do let some (_, a, C) := e.app3? ``circlesInter | none return (a, C) def isPoint? (e : Expr) : Bool := e.isAppOf ``Point def isLine? (e : Expr) : Bool := e.isAppOf ``Line /-! # Utilities for constructing diagrams -/ open DiagramBuilderM in def addHypotheses (hyps : Array LocalDecl) : DiagramBuilderM Unit := do for h in hyps do let tp ← instantiateMVars h.type if isPoint? tp then discard $ addExpr "Point" h.toExpr if isLine? tp then discard $ addExpr "Line" h.toExpr if let some (a, b, c) := isBetweenPred? tp then let sa ← addExpr "Point" a let sb ← addExpr "Point" b let sc ← addExpr "Point" c addInstruction s!"Between({sa}, {sb}, {sc})" if let some (a, L) := isOnLinePred? tp then let sa ← addExpr "Point" a let sL ← addExpr "Line" L addInstruction s!"OnLine({sa}, {sL})" if let some (a, C) := isOnCirclePred? tp then let sa ← addExpr "Point" a let sC ← addExpr "Circle" C addInstruction s!"OnCircle({sa}, {sC})" if let some (a, C) := isInCirclePred? tp then let sa ← addExpr "Point" a let sC ← addExpr "Circle" C addInstruction s!"InCircle({sa}, {sC})" if let some (a, C) := isCenterCirclePred? tp then let sa ← addExpr "Point" a let sC ← addExpr "Circle" C addInstruction s!"CenterCircle({sa}, {sC})" if let some (C, D) := isCirclesInterPred? tp then let sC ← addExpr "Circle" C let sD ← addExpr "Circle" D addInstruction s!"CirclesInter({sC}, {sD})" /-! # Implementation of the widget -/ def EuclideanDisplay.dsl := include_str ".."/".."/"widget"/"penrose"/"euclidean.dsl" def EuclideanDisplay.sty := include_str ".."/".."/"widget"/"penrose"/"euclidean.sty" open scoped Jsx in @[server_rpc_method] def EuclideanDisplay.rpc (props : PanelWidgetProps) : RequestM (RequestTask Html) := RequestM.asTask do let inner : Html ← (do -- Are there any goals unsolved? If so, pick the first one. if props.goals.isEmpty then return <span>No goals.</span> let some g := props.goals[0]? | unreachable! -- Execute the next part using the metavariable context and local context of the goal. g.ctx.val.runMetaM {} do let md ← g.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do -- Which hypotheses have been selected in the UI, -- meaning they should *not* be shown in the display. let mut hiddenLocs : Std.HashSet FVarId := .emptyWithCapacity props.selectedLocations.size for l in props.selectedLocations do match l with | ⟨mv, .hyp fv⟩ | ⟨mv, .hypType fv _⟩ => if mv == g.mvarId then hiddenLocs := hiddenLocs.insert fv | _ => continue -- Filter local declarations by whether they are not in `hiddenLocs`. let locs := (← getLCtx).decls.toArray.filterMap (fun d? => if let some d := d? then if !hiddenLocs.contains d.fvarId then some d else none else none) -- Produce the diagram. DiagramBuilderM.run do addHypotheses locs match ← DiagramBuilderM.buildDiagram dsl sty with | some html => return html | none => return <span>No Euclidean goal.</span>) return <details «open»={true}> <summary className="mv2 pointer">Euclidean diagram</summary> <div className="ml1">{inner}</div> </details> @[widget_module] def EuclideanDisplay : Component PanelWidgetProps := mk_rpc_widget% EuclideanDisplay.rpc /-! # Example usage -/ variable [i : IncidenceGeometry] example {a b c : Point} {L M : Line} (Babc : between a b c) (aL : onLine a L) (bM : onLine b M) (cL : onLine c L) (cM : onLine c M) : L = M := by with_panel_widgets [EuclideanDisplay] -- Place your cursor here. have bc := ne_23_of_between Babc have bL := onLine_2_of_between Babc aL cL exact line_unique_of_pts bc bL cL bM cM /-! # Euclidean constructions -/ open DiagramBuilderM Jsx in /-- Add every possible line between any two points in `hyps` to the diagram. Lines are labelled with links to insert them into the proof script. -/ def constructLines (hyps : Array LocalDecl) (docMeta : Server.DocumentMeta) (cursorPos : Lsp.Position) : DiagramBuilderM Unit := do -- Identify objects and hypotheses from which constructions can be made. let mut points : Array LocalDecl := {} let mut circleInters : Array (LocalDecl × LocalDecl × LocalDecl) := {} for h in hyps do let tp ← instantiateMVars h.type if isPoint? tp then points := points.push h if let some (.fvar C, .fvar D) := isCirclesInterPred? tp then circleInters := circleInters.push (h, ← C.getDecl, ← D.getDecl) -- Add a plausible construction, labelled with a link that makes the text edit. let addConstruction (nm tp ctr : String) : DiagramBuilderM Unit := do addEmbed nm tp ( <span> <b>{.text nm}</b> ({ .ofComponent MakeEditLink (MakeEditLinkProps.ofReplaceRange docMeta ⟨cursorPos, cursorPos⟩ ctr) #[.text "insert"] }) </span>) addInstruction s!"Emphasize({nm})" -- Construct every possible line and circle. for hi : i in [0:points.size] do let p := points[i] let sp ← addExpr "Point" p.toExpr for hj : j in [i+1:points.size] do let q := points[j] let sq ← addExpr "Point" q.toExpr -- Add the line. let nm := s!"{sp}{sq}" addConstruction nm "Line" s!"let ⟨{nm}, _, _⟩ := line_of_pts {sp} {sq}" addInstruction s!"OnLine({sp}, {nm})" addInstruction s!"OnLine({sq}, {nm})" -- Add two possible circles. let nm := s!"C{sp}{sq}" addConstruction nm "Circle" s!"let ⟨{nm}, _, _⟩ := circle_of_ne {sp} {sq} (by assumption)" addInstruction s!"CenterCircle({sp}, {nm})" addInstruction s!"OnCircle({sq}, {nm})" let nm := s!"C{sq}{sp}" addConstruction nm "Circle" s!"let ⟨{nm}, _, _⟩ := circle_of_ne {sq} {sp} (by assumption)" addInstruction s!"CenterCircle({sq}, {nm})" addInstruction s!"OnCircle({sp}, {nm})" -- Construct every possible circle intersection. for hi : i in [0:circleInters.size] do let (h, C, D) := circleInters[i] let sC ← addExpr "Circle" C.toExpr let sD ← addExpr "Circle" D.toExpr let nm := s!"{sC}{sD}" let nm' := s!"{sD}{sC}" addConstruction nm "Point" s!"let ⟨{nm}, {nm'}, _, _, _, _, _⟩ := pts_of_circlesInter {h.userName}" addEmbed nm' "Point" <b>{.text nm'}</b> addInstruction s!"OnCircle({nm'}, {sC})" addInstruction s!"OnCircle({nm}, {sD})" addInstruction s!"OnCircle({nm}, {sC})" addInstruction s!"OnCircle({nm'}, {sD})" open scoped Jsx in @[server_rpc_method] def EuclideanConstructions.rpc (props : PanelWidgetProps) : RequestM (RequestTask Html) := RequestM.asTask do let doc ← RequestM.readDoc let inner : Html ← (do -- Are there any goals unsolved? If so, pick the first one. if props.goals.isEmpty then return <span>No goals.</span> let some g := props.goals[0]? | unreachable! -- Execute the next part using the metavariable context and local context of the goal. g.ctx.val.runMetaM {} do let md ← g.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do -- Grab all hypotheses from the local context. let allHyps := (← getLCtx).decls.toArray.filterMap id -- Find which hypotheses are selected. let selectedHyps ← props.selectedLocations.filterMapM fun | ⟨mv, .hyp fv⟩ | ⟨mv, .hypType fv _⟩ => if mv == g.mvarId then return some (← fv.getDecl) else return none | _ => return none -- Produce the diagram. DiagramBuilderM.run do addHypotheses allHyps constructLines selectedHyps doc.meta props.pos match ← DiagramBuilderM.buildDiagram EuclideanDisplay.dsl EuclideanDisplay.sty 1500 with | some html => return html | none => return <span>No Euclidean goal.</span>) -- Return a collapsible `<details>` block around our widget. return <details «open»={true}> <summary className="mv2 pointer">Euclidean constructions</summary> <div className="ml1">{inner}</div> </details> @[widget_module] def EuclideanConstructions : Component PanelWidgetProps := mk_rpc_widget% EuclideanConstructions.rpc axiom test_sorry {α} : α show_panel_widgets [local EuclideanConstructions] /-! # Example construction -/ /- Try constructing an equilateral triangle abc with line segment ab as the base. Place your cursor in the proof below. To make a construction involving objects `x, y, z`, shift-click their names in 'Tactic state' in order to select them. Due to a limitation of the widget, you can only click-to-select in 'Tactic state', and not in the diagram. - To construct a line on two points, select `a` and `b` in `a b : Point`. - To construct a circle with center `a` passing through `b`, select `a` and `b` in `a b : Point`. You may have to prove that `a ≠ b`. - To construct an intersection point of two circles `C` and `D`, you first have to provide a local proof of `have h : circlesInter C D := ...` (i.e., show that the circles intersect) using the axioms of `IncidenceGeometry` above. Then select `h` in `h : circlesInter C D`. -/ example {a b : Point} (_hab : a ≠ b) : ∃ L M c, onLine a L ∧ onLine b M ∧ onLine c M ∧ onLine c L := by -- Place your cursor here. exact test_sorry
.lake/packages/proofwidgets/ProofWidgets/Demos/SelectInsertConv.lean
module public meta import Lean.Meta.ExprLens public meta import ProofWidgets.Data.Html public meta import ProofWidgets.Component.OfRpcMethod public meta import ProofWidgets.Component.MakeEditLink public meta import ProofWidgets.Component.Panel.Basic public meta section open Lean Meta Server open ProofWidgets /-! # The conv? example This demo defines a `conv?` tactic that displays a widget for point-and-click `conv` insertion. Whenever the user selects a subter, of the goal in the tactic state, the widget will display a button that, upon being clicked, replaces the `conv?` call with a `conv => enter [...]` call zooming in on the selected subterm. -/ private structure SolveReturn where expr : Expr val? : Option String listRest : List Nat private def solveLevel (expr : Expr) (path : List Nat) : MetaM SolveReturn := match expr with | Expr.app _ _ => do let mut descExp := expr let mut count := 0 let mut explicitList := [] -- we go through the application until we reach the end, counting how many explicit arguments -- it has and noting whether they are explicit or implicit while descExp.isApp do if (←Lean.Meta.inferType descExp.appFn!).bindingInfo!.isExplicit then explicitList := true::explicitList count := count + 1 else explicitList := false::explicitList descExp := descExp.appFn! -- we get the correct `enter` command by subtracting the number of `true`s in our list let mut mutablePath := path let mut length := count explicitList := List.reverse explicitList while !mutablePath.isEmpty && mutablePath.head! == 0 do if explicitList.head! == true then count := count - 1 explicitList := explicitList.tail! mutablePath := mutablePath.tail! let mut nextExp := expr while length > count do nextExp := nextExp.appFn! length := length - 1 nextExp := nextExp.appArg! let pathRest := if mutablePath.isEmpty then [] else mutablePath.tail! return { expr := nextExp, val? := toString count , listRest := pathRest } | Expr.lam n _ b _ => do let name := match n with | Name.str _ s => s | _ => panic! "no name found" return { expr := b, val? := name, listRest := path.tail! } | Expr.forallE n _ b _ => do let name := match n with | Name.str _ s => s | _ => panic! "no name found" return { expr := b, val? := name, listRest := path.tail! } | Expr.mdata _ b => do match b with | Expr.mdata _ _ => return { expr := b, val? := none, listRest := path } | _ => return { expr := b.appFn!.appArg!, val? := none, listRest := path.tail!.tail! } | _ => do return { expr := ←(Lean.Core.viewSubexpr path.head! expr) val? := toString (path.head! + 1) listRest := path.tail! } open Lean Syntax in def insertEnter (locations : Array Lean.SubExpr.GoalsLocation) (goalType : Expr) : MetaM String := do let some pos := locations[0]? | throwError "You must select something." let ⟨_, .target subexprPos⟩ := pos | throwError "You must select something in the goal." let mut list := (SubExpr.Pos.toArray subexprPos).toList let mut expr := goalType let mut retList := [] -- generate list of commands for `enter` while !list.isEmpty do let res ← solveLevel expr list expr := res.expr retList := match res.val? with | none => retList | some val => val::retList list := res.listRest -- build `enter [...]` string retList := List.reverse retList let mut enterval := "conv => enter " ++ toString retList if enterval.contains '0' then enterval := "Error: Not a valid conv target" if retList.isEmpty then enterval := "" return enterval def findGoalForLocation (goals : Array Widget.InteractiveGoal) (loc : SubExpr.GoalsLocation) : Option Widget.InteractiveGoal := goals.find? (·.mvarId == loc.mvarId) structure ConvSelectionPanelProps extends PanelWidgetProps where /-- The range in the source document where the `conv` command will be inserted. -/ replaceRange : Lsp.Range deriving RpcEncodable open scoped Jsx in @[server_rpc_method] def ConvSelectionPanel.rpc (props : ConvSelectionPanelProps) : RequestM (RequestTask Html) := RequestM.asTask do let doc ← RequestM.readDoc let inner : Html ← (do if props.selectedLocations.isEmpty then return <span>Use shift-click to select one sub-expression in the goal that you want to zoom on.</span> let some selectedLoc := props.selectedLocations[0]? | unreachable! let some g := findGoalForLocation props.goals selectedLoc | throw $ .invalidParams s!"could not find goal for location {toJson selectedLoc}" g.ctx.val.runMetaM {} do let md ← g.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do let newCode ← insertEnter props.selectedLocations md.type return .ofComponent MakeEditLink (.ofReplaceRange doc.meta props.replaceRange newCode) #[ .text newCode ]) return <details «open»={true}> <summary className="mv2 pointer">Conv 🔍</summary> <div className="ml1">{inner}</div> </details> @[widget_module] def ConvSelectionPanel : Component ConvSelectionPanelProps := mk_rpc_widget% ConvSelectionPanel.rpc open scoped Json in elab stx:"conv?" : tactic => do let some replaceRange := (← getFileMap).lspRangeOfStx? stx | return Widget.savePanelWidgetInfo ConvSelectionPanel.javascriptHash (pure $ json% { replaceRange: $(replaceRange) }) stx -- Like `sorry` but avoids a warning for demonstration purposes. axiom test_sorry {α} : α example (a : Nat) : a + a - a + a = a := by conv? -- Put your cursor on the next line all_goals exact test_sorry
.lake/packages/proofwidgets/ProofWidgets/Demos/Venn.lean
module public meta import Lean.Elab.Tactic public meta import ProofWidgets.Component.Panel.Basic public meta import ProofWidgets.Component.PenroseDiagram public meta import ProofWidgets.Component.HtmlDisplay public meta import ProofWidgets.Component.OfRpcMethod public meta section open Lean Meta Server open ProofWidgets /-! # Minimal definiton of sets copied from Mathlib -/ @[expose] def Set (α : Type u) := α → Prop namespace Set /-- Membership in a set -/ protected def Mem (s : Set α) (a : α) : Prop := s a instance : Membership α (Set α) := ⟨Set.Mem⟩ theorem ext {a b : Set α} (h : ∀ (x : α), x ∈ a ↔ x ∈ b) : a = b := funext (fun x ↦ propext (h x)) protected def Subset (s₁ s₂ : Set α) := ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂ /-- Porting note: we introduce `≤` before `⊆` to help the unifier when applying lattice theorems to subset hypotheses. -/ instance : LE (Set α) := ⟨Set.Subset⟩ instance : HasSubset (Set α) := ⟨(· ≤ ·)⟩ end Set /-! # Metaprogramming utilities to break down set expressions -/ /-- If `e == S ⊆ T` return `some (S, T)`, otherwise `none`. -/ def isSubsetPred? (e : Expr) : Option (Expr × Expr) := do let some (_, _, S, T) := e.app4? ``HasSubset.Subset | none return (S, T) /-- Expressions to display as labels in a diagram. -/ abbrev ExprEmbeds := Array (String × Expr) open scoped Jsx in def mkSetDiag (sub : String) (embeds : ExprEmbeds) : MetaM Html := do let embeds ← embeds.mapM fun (s, h) => return (s, <InteractiveCode fmt={← Widget.ppExprTagged h} />) return <PenroseDiagram embeds={embeds} dsl={include_str ".."/".."/"widget"/"penrose"/"setTheory.dsl"} sty={include_str ".."/".."/"widget"/"penrose"/"venn.sty"} sub={sub} /> def isSetGoal? (hyps : Array LocalDecl) : MetaM (Option Html) := do let mut sub := "AutoLabel All\n" let mut sets : Std.HashMap String Expr := ∅ for assm in hyps do let tp ← instantiateMVars assm.type if let some (S, T) := isSubsetPred? tp then let sS ← toString <$> Lean.Meta.ppExpr S let sT ← toString <$> Lean.Meta.ppExpr T let (cS, sets') := sets.containsThenInsert sS S let (cT, sets') := sets'.containsThenInsert sT T sets := sets' if !cS then sub := sub ++ s!"Set {sS}\n" if !cT then sub := sub ++ s!"Set {sT}\n" sub := sub ++ s!"IsSubset({sS}, {sT})\n" if sets.isEmpty then return none some <$> mkSetDiag sub sets.toArray /-! # Implementation of the widget -/ def findGoalForLocation (goals : Array Widget.InteractiveGoal) (loc : SubExpr.GoalsLocation) : Option Widget.InteractiveGoal := goals.find? (·.mvarId == loc.mvarId) open scoped Jsx in @[server_rpc_method] def VennDisplay.rpc (props : PanelWidgetProps) : RequestM (RequestTask Html) := RequestM.asTask do let inner : Html ← (do if props.selectedLocations.isEmpty then return <span>Use shift-click to select hypotheses to include in the diagram.</span> let some selectedLoc := props.selectedLocations[0]? | unreachable! let some g := findGoalForLocation props.goals selectedLoc | throw $ .invalidParams s!"could not find goal for location {toJson selectedLoc}" g.ctx.val.runMetaM {} do let md ← g.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do let locs : Array LocalDecl ← props.selectedLocations.filterMapM fun | ⟨mv, .hyp fv⟩ | ⟨mv, .hypType fv _⟩ => if mv == g.mvarId then return some (← fv.getDecl) else return none | _ => return none match ← isSetGoal? locs with | some html => return html | none => return <span>No set goal.</span>) return <details «open»={true}> <summary className="mv2 pointer">Venn diagram</summary> <div className="ml1">{inner}</div> </details> @[widget_module] def VennDisplay : Component PanelWidgetProps := mk_rpc_widget% VennDisplay.rpc /-! # Example usage -/ example {R S T U : Set Nat} : S ⊆ U → T ⊆ U → R ⊆ S → R ⊆ U := by with_panel_widgets [VennDisplay] intro h₁ _ h₃ -- Place your cursor here. exact fun n h => h |> h₃ |> h₁
.lake/packages/proofwidgets/ProofWidgets/Demos/RbTree.lean
module public meta import ProofWidgets.Presentation.Expr public meta import ProofWidgets.Component.Panel.SelectionPanel public meta section /-! ## References: - Chris Okasaki. "Functional Pearls: Red-Black Trees in a Functional Setting". 1993 -/ inductive RBColour where | red | black inductive RBTree (α : Type u) where | empty : RBTree α | node (color : RBColour) (l : RBTree α) (a : α) (r : RBTree α) : RBTree α namespace RBTree def contains [Ord α] (a : α) : RBTree α → Bool | empty => false | node _ l b r => match compare a b with | .lt => l.contains a | .eq => true | .gt => r.contains a def balance : RBColour → RBTree α → α → RBTree α → RBTree α | .black, (node .red (node .red a x b) y c), z, d | .black, (node .red a x (node .red b y c)), z, d | .black, a, x, (node .red (node .red b y c) z d) | .black, a, x, (node .red b y (node .red c z d)) => node .red (node .black a x b) y (node .black c z d) | color, a, x, b => node color a x b def insert [Ord α] (a : α) (s : RBTree α) : RBTree α := makeBlack (ins s) where ins : RBTree α → RBTree α | empty => node .red empty a empty | node c l b r => match compare a b with | .lt => balance c (ins l) b r | .eq => node c l b r | .gt => balance c l b (ins r) makeBlack : RBTree α → RBTree α | empty => empty | node _ l b r => node .black l b r end RBTree /-! # Metaprogramming utilities for red-black trees -/ open Lean def empty? (e : Expr) : Bool := e.app1? ``RBTree.empty matches some _ @[inline] def Lean.Expr.app5? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr × Expr × Expr) := if e.isAppOfArity fName 5 then some ( e.appFn!.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg!) else none def node? (e : Expr) : Option (Expr × Expr × Expr × Expr) := do let some (_, color, l, a, r) := e.app5? ``RBTree.node | none return (color, l, a, r) unsafe def evalColourUnsafe (e : Expr) : MetaM RBColour := Lean.Meta.evalExpr' RBColour ``RBColour e @[implemented_by evalColourUnsafe] opaque evalColour (e : Expr) : MetaM RBColour /-- Like `RBTreeColour`, but with `blue` standing in for unknown, symbolic `c : RBTreeColour`. -/ inductive RBTreeVarsColour where | red | black | blue deriving FromJson, ToJson open Widget in /-- Like `RBTree` but with concrete node contents replaced by quoted, pretty-printed code, and an extra constructor for similarly pretty-printed symbolic subtrees. Tangent: what is the transformation of polynomial functors from the original type to one with this kind of symbolic data? -/ inductive RBTreeVars where | empty : RBTreeVars | var : CodeWithInfos → RBTreeVars | node (color : RBTreeVarsColour) (l : RBTreeVars) (a : CodeWithInfos) (r : RBTreeVars) : RBTreeVars deriving Server.RpcEncodable /-! # `Expr` presenter to display red-black trees -/ structure RBDisplayProps where tree : RBTreeVars deriving Server.RpcEncodable open ProofWidgets @[widget_module] def RBDisplay : Component RBDisplayProps where javascript := include_str ".." / ".." / ".lake" / "build" / "js" / "rbTree.js" open scoped Jsx in partial def drawTree? (e : Expr) : MetaM (Option Html) := do if let some _ := node? e then return some <RBDisplay tree={← go e}/> else if empty? e then return some <RBDisplay tree={← go e}/> else return none where go (e : Expr) : MetaM RBTreeVars := do if let some (color, l, a, r) := node? e then let color ← try match ← evalColour color with | .red => pure .red | .black => pure .black catch _ => pure .blue return .node color (← go l) (← Widget.ppExprTagged a) (← go r) else if empty? e then return .empty else return .var (← Widget.ppExprTagged e) @[expr_presenter] def RBTree.presenter : ExprPresenter where userName := "Red-black tree" present e := do let some t ← drawTree? e | throwError "not a tree :(" return t /-! # Example -/ open RBTree RBColour in example {α : Type} (x y z : α) (a b c d : RBTree α) (h : ¬ ∃ e w f, a = node red e w f) : balance black (node red a x (node red b y c)) z d = node red (node black a x b) y (node black c z d) := by with_panel_widgets [SelectionPanel] match a with | .empty => simp [balance] | node black .. => simp [balance] | node red .. => conv => unfold balance; simp_match exact False.elim <| h ⟨_, _, _, rfl⟩
.lake/packages/proofwidgets/ProofWidgets/Demos/Plot.lean
module public meta import ProofWidgets.Component.HtmlDisplay public meta import ProofWidgets.Component.Recharts public meta section open Lean ProofWidgets Recharts def fn (t : Float) (x : Float): Float := 50 * (x - 0.25) * (x - 0.5) * (x - 0.7) + 0.1 * (x * 40 - t * 2 * 3.141).sin open scoped ProofWidgets.Jsx in def Plot (fn : Float → Float) (steps := 100) : Html := let jsonData : Array Json := Array.range (steps + 1) |> Array.map (fun (x : Nat) => let x : Float := x.toFloat / steps.toFloat; (x, fn x)) |> Array.map (fun (x,y) => json% {x: $(toJson x) , y: $(toJson y)}); <LineChart width={400} height={400} data={jsonData}> <XAxis domain?={#[toJson 0, toJson 1]} dataKey?="x" /> <YAxis domain?={#[toJson (-1), toJson 1]} allowDataOverflow={Bool.false} /> <Line type={.monotone} dataKey="y" stroke="#8884d8" dot?={Bool.false} /> </LineChart> #html Plot (fn 0) #html Plot (fn 0.2) #html Plot (fn 0.4) #html Plot (fn 0.6) /-! # Bonus demo: animated plots! -/ def mkFrames (fn : Float → Float → Float) (steps := 100) : Array Html:= List.range (steps + 1) |>.toArray |>.map (fun t => Plot (fn (t.toFloat / steps.toFloat))) structure AnimatedHtmlProps where frames : Array Html framesPerSecond? : Option Nat := none deriving Server.RpcEncodable @[widget_module] def AnimatedHtml : Component AnimatedHtmlProps where javascript := include_str ".." / ".." / ".lake" / "build" / "js" / "animatedHtml.js" open scoped ProofWidgets.Jsx in -- put your cursor on the below line to see an animated widget #html <AnimatedHtml frames={mkFrames fn} framesPerSecond?={some 60} />
.lake/packages/proofwidgets/ProofWidgets/Demos/ExprPresentation.lean
module public meta import ProofWidgets.Component.Panel.SelectionPanel public meta import ProofWidgets.Component.Panel.GoalTypePanel public meta section open ProofWidgets Jsx @[expr_presenter] def presenter : ExprPresenter where userName := "With octopodes" layoutKind := .inline present e := return <span> {.text "🐙 "}<InteractiveCode fmt={← Lean.Widget.ppExprTagged e} />{.text " 🐙"} </span> example : 2 + 2 = 4 ∧ 3 + 3 = 6 := by with_panel_widgets [GoalTypePanel] -- Place cursor here. constructor rfl rfl example (_h : 2 + 2 = 5) : 2 + 2 = 4 := by with_panel_widgets [SelectionPanel] -- Place cursor here and select subexpressions in the goal with shift-click. rfl
.lake/packages/proofwidgets/ProofWidgets/Demos/Jsx.lean
module public meta import ProofWidgets.Component.HtmlDisplay public meta section -- The `ProofWidgets.Jsx` namespace provides JSX-like notation for HTML open scoped ProofWidgets.Jsx -- Put your cursor over this #html <b>What, HTML in Lean?!</b> -- String-valued attributes can be written directly, or interpolated with `{ }` #html <img src={"https://" ++ "upload.wikimedia.org/wikipedia/commons/a/a5/Parrot_montage.jpg"} alt="Six photos of parrots arranged in a grid." /> def htmlLetters : Array ProofWidgets.Html := #[ <span style={json% {color: "red"}}>H</span>, <span style={json% {color: "yellow"}}>T</span>, <span style={json% {color: "green"}}>M</span>, <span style={json% {color: "blue"}}>L</span> ] -- HTML children can be interpolated with `{ }` (single node) and `{... }` (multiple nodes) def x := <b>You can use {...htmlLetters} in Lean {.text s!"{1 + 3}"}! <hr/> </b> #html x -- Use `MarkdownDisplay` to render Markdown open ProofWidgets in #html <MarkdownDisplay contents={" ## Hello, Markdown We have **bold text**, _italic text_, `example : True := by trivial`, and $3×19 = \\int\\limits_0^{57}1~dx$. "} /> -- HTML trees can also be produced by metaprograms open ProofWidgets Lean Server Elab in #html (do let e ← Term.elabTerm (← ``(1 + 3)) (mkConst ``Nat) Term.synthesizeSyntheticMVarsNoPostponing let e ← instantiateMVars e return <InteractiveExpr expr={← WithRpcRef.mk (← ExprWithCtx.save e)} /> : Term.TermElabM Html)
.lake/packages/proofwidgets/ProofWidgets/Demos/InteractiveSvg.lean
module public meta import ProofWidgets.Component.InteractiveSvg public meta import ProofWidgets.Component.HtmlDisplay public meta section open Lean open ProofWidgets Svg Jsx abbrev State := Array (Float × Float) def isvg : InteractiveSvg State where init := #[(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)] frame := { xmin := -1 ymin := -1 xSize := 2 width := 400 height := 400 } update _time _Δt _action _mouseStart mouseEnd _selected getData state := match getData Nat, mouseEnd with | some id, some p => state.set! id p.toAbsolute | _, _ => state render _time mouseStart mouseEnd state := { elements := let mousePointer := match mouseStart, mouseEnd with | some s, some e => #[ Svg.circle e (.px 5) |>.setFill (1.,1.,1.), Svg.line s e |>.setStroke (1.,1.,1.) (.px 2) ] | _, _ => #[] let circles := (state.mapIdx fun idx (p : Float × Float) => Svg.circle p (.abs 0.2) |>.setFill (0.7,0.7,0.7) |>.setId s!"circle{idx}" |>.setData idx ) mousePointer.append circles } open Server RequestM in @[server_rpc_method] def updateSvg (params : UpdateParams State) : RequestM (RequestTask (UpdateResult State)) := isvg.serverRpcMethod params @[widget_module] def SvgWidget : Component (UpdateResult State) where javascript := include_str ".." / ".." / ".lake" / "build" / "js" / "interactiveSvg.js" def init : UpdateResult State := { html := <div>Init!!!</div>, state := { state := isvg.init time := 0 selected := none mousePos := none idToData := isvg.render 0 none none isvg.init |>.idToDataList} } #html <SvgWidget html={init.html} state={init.state}/>
.lake/packages/proofwidgets/ProofWidgets/Demos/Macro.lean
module public meta import ProofWidgets.Component.HtmlDisplay public meta section -- See the `Jsx.lean` demo for more about JSX. open scoped ProofWidgets.Jsx /-! # Widgets in macros Macros may expand to commands or terms that end up saving widget info, but the syntax to which the widget info is associated must be marked as `canonical` for the widget to be displayed. -/ def Lean.SourceInfo.mkCanonical : SourceInfo → SourceInfo | .synthetic s e _ => .synthetic s e true | si => si def Lean.Syntax.mkInfoCanonical : Syntax → Syntax | .missing => .missing | .node i k a => .node i.mkCanonical k a | .atom i v => .atom i.mkCanonical v | .ident i r v p => .ident i.mkCanonical r v p def Lean.TSyntax.mkInfoCanonical : TSyntax k → TSyntax k := (.mk ·.raw.mkInfoCanonical) macro "#browse " src:term : command => Lean.TSyntax.mkInfoCanonical <$> `(#html <iframe src={$src} width="100%" height="600px" />) #browse "https://leanprover-community.github.io/" -- Do you like recursion? #browse "https://lean.math.hhu.de"
.lake/packages/proofwidgets/ProofWidgets/Demos/LazyComputation.lean
module public meta import ProofWidgets.Component.Basic public meta section open ProofWidgets open Lean Meta Server Elab Tactic /-- A `MetaM String` continuation, containing both the computation and all monad state. -/ structure MetaMStringCont where ci : Elab.ContextInfo lctx : LocalContext -- We can only derive `TypeName` for type constants, so this must be monomorphic. k : MetaM String deriving TypeName structure RunnerWidgetProps where /-- A continuation to run and print the results of when the button is clicked. -/ k : WithRpcRef MetaMStringCont -- Make it possible for widgets to receive `RunnerWidgetProps`. Uses the `TypeName` instance. deriving RpcEncodable @[server_rpc_method] def runMetaMStringCont : RunnerWidgetProps → RequestM (RequestTask String) | {k := ref} => RequestM.asTask do let {ci, lctx, k} := ref.val ci.runMetaM lctx k @[widget_module] def runnerWidget : Component RunnerWidgetProps where javascript := " import { RpcContext, mapRpcError } from '@leanprover/infoview' import * as React from 'react'; const e = React.createElement; export default function(props) { const [contents, setContents] = React.useState('Run!') const rs = React.useContext(RpcContext) return e('button', { onClick: () => { setContents('Running..') rs.call('runMetaMStringCont', props) .then(setContents) .catch(e => { setContents(mapRpcError(e).message) }) }}, contents) } " syntax (name := makeRunnerTac) "make_runner" : tactic @[tactic makeRunnerTac] def makeRunner : Tactic | `(tactic| make_runner%$tk) => do let x : MetaM String := do return "Hello, world!" -- Store the continuation and monad context. let props : RunnerWidgetProps := { k := ← WithRpcRef.mk { ci := { ← CommandContextInfo.save with } lctx := (← getLCtx) k := x } } -- Save a widget together with a pointer to `props`. Widget.savePanelWidgetInfo runnerWidget.javascriptHash (rpcEncode props) tk | _ => throwUnsupportedSyntax example : True := by make_runner trivial
.lake/packages/proofwidgets/ProofWidgets/Demos/Rubiks.lean
module public meta import ProofWidgets.Component.HtmlDisplay public meta section open Lean ProofWidgets open scoped ProofWidgets.Jsx structure RubiksProps where seq : Array String := #[] deriving ToJson, FromJson, Inhabited @[widget_module] def Rubiks : Component RubiksProps where javascript := include_str ".." / ".." / ".lake" / "build" / "js" / "rubiks.js" def eg := #["L", "L", "D⁻¹", "U⁻¹", "L", "D", "D", "L", "U⁻¹", "R", "D", "F", "F", "D"] #html <Rubiks seq={eg} />
.lake/packages/proofwidgets/ProofWidgets/Demos/Graph/Basic.lean
module public meta import ProofWidgets.Component.GraphDisplay public meta import ProofWidgets.Component.HtmlDisplay public meta section /-! ## Directed graphs with `GraphDisplay` -/ open ProofWidgets Jsx /-! ### Basic usage -/ def mkEdge (st : String × String) : GraphDisplay.Edge := {source := st.1, target := st.2} -- Place your cursor here. #html <GraphDisplay vertices={#["a", "b", "c", "d", "e", "f"].map ({id := ·})} edges={#[("b","c"), ("d","e"), ("e","f"), ("f","d")].map mkEdge} /> /-! ### Custom layout Forces acting on the vertices can be customized in order to control graph layout. -/ def complete (n : Nat) : Array GraphDisplay.Vertex × Array GraphDisplay.Edge := Id.run do let mut verts := #[] let mut edges := #[] for i in [:n] do verts := verts.push {id := toString i} for j in [:i] do edges := edges.push {source := toString i, target := toString j} edges := edges.push {source := toString j, target := toString i} return (verts, edges) def K₁₀ := complete 10 #html <GraphDisplay vertices={K₁₀.1} edges={K₁₀.2} -- Specify forces here. forces={#[ .link { distance? := some 150 } ]} /> /-! ### Vertex labels Arbitrary SVG elements can be used as vertex labels. -/ #html <GraphDisplay vertices={#[ { id := "a" -- Specify a label here. label := <circle r={5} fill="#ff0000" /> }, { id := "b" -- Use `<foreignObject>` to draw non-SVG elements. label := <foreignObject height={50} width={50}> -- TODO: the extra `<p>` node messes up positioning <MarkdownDisplay contents="$xyz$" /> </foreignObject> } ]} edges={#[{ source := "a", target := "b" }]} /> /-! ### Edge labels Arbitrary SVG elements can be used as edge labels. -/ #html <GraphDisplay vertices={#["a", "b", "c"].map ({ id := ·})} edges={#[ { source := "a", target := "b" -- Specify a label here. label? := <g> {GraphDisplay.mkCircle #[("r", "10")]} <text textAnchor="middle" dominantBaseline="middle">1</text> </g> }, { source := "b", target := "c" -- Use `<foreignObject>` to draw non-SVG elements. label? := <foreignObject height={50} width={50}> -- TODO: the extra `<p>` node messes up positioning <MarkdownDisplay contents="$e_2$" /> </foreignObject> } ]} forces={#[ .link { distance? := some 100 } ]} /> /-! ### Extra details A details box with extra information can be displayed below the graph. Click on vertices and edges to view their details. -/ #html <GraphDisplay vertices={#[ { id := "a" -- Specify details here. details? := Html.text "Vertex a." -- Add class to indicate clickability. label := GraphDisplay.mkCircle #[("className", "dim")] }, { id := "b" } ]} edges={#[ { source := "a", target := "b" details? := Html.text "Edge a → b." attrs := #[("className", "dim"), ("strokeWidth", 3)] } ]} -- Set this to display details. showDetails={true} />
.lake/packages/proofwidgets/ProofWidgets/Demos/Graph/MVarGraph.lean
module public meta import ProofWidgets.Component.GraphDisplay public meta import ProofWidgets.Component.Panel.Basic public meta import ProofWidgets.Component.OfRpcMethod public meta section /-! This demo visualizes the graph of metavariable assignments in tactic proofs. -/ universe u v open Lean Meta /-- Adjacency list representation of a directed graph with labelled edges. -/ abbrev Graph (α β : Type u) [BEq α] [Hashable α] := Std.HashMap α (List (α × β)) variable {α β : Type u} [BEq α] [Hashable α] /-- Filter out vertices not reachable from a vertex in `vs`. -/ def Graph.filterReachable (g : Graph α β) (vs : List α) : Graph α β := Id.run do let mut work := vs let mut reached := Std.HashSet.ofList vs -- FIXME: `do` notation freaks out if `a` and `β` live in different universes while h : !work.isEmpty do let v := work.head (by simpa using h) work := work.tail for (u, _) in g.get? v |>.getD [] do if !reached.contains u then work := u :: work reached := reached.insert u return g.filter fun v _ => reached.contains v /-- Return the user name if it exists, otherwise the prettified underlying name. -/ def _root_.Lean.MVarId.getName (m : MVarId) : MetaM Name := do let d ← m.getDecl if !d.userName.isAnonymous then return d.userName let .num _ n := m.name | return m.name return Name.anonymous.str "m" |>.num n /-- Return the graph of metavariables, where a `true` edge `m → n` exists iff `n` is assigned an expression that uses `m`, and a `false` edge `m → n` exists iff the type of `n` depends on `m`. -/ def buildMVarGraph : MetaM (Graph MVarId Bool) := do let mut g : Graph MVarId Bool := {} for (m, _) in (← getMCtx).decls do g := g.alter m (·.getD []) if let some e := (← getMCtx).eAssignment.find? m then for n in (e.collectMVars {}).result do g := g.alter n ((m, true) :: ·.getD []) if let some a := (← getMCtx).dAssignment.find? m then let n := a.mvarIdPending g := g.alter n ((m, true) :: ·.getD []) for n in ((← m.getType).collectMVars {}).result do g := g.alter n ((m, false) :: ·.getD []) return g open ProofWidgets Jsx in def mkLabel (e : MVarId) (stroke := "var(--vscode-editor-foreground)") (fill := "var(--vscode-editor-background)") : MetaM (Nat × Nat × Html) := do let fmt := s!"?{← e.getName}" let fmtTp ← withOptions (·.setNat `pp.deepTerms.threshold 2) (toString <$> ppExpr (← e.getType')) let len := fmt.length + fmtTp.length + 3 let w := min (15 + len * 6) 100 let h := max 20 (20 * (1 + len / 15)) let x : Int := -w/2 let y : Int := -h/2 return (w, h, <g> <rect fill={fill} stroke={stroke} strokeWidth={.num 1.5} width={w} height={h} x={x} y={y} rx={5} /> <foreignObject width={w} height={h} x={.num (x + 5 : Int)} y={y}> <span className="font-code">{.text fmt} : {.text fmtTp}</span> </foreignObject> </g> ) open ProofWidgets Jsx in def drawMVarGraph (goals : List MVarId) : MetaM Html := do let mvars ← buildMVarGraph let mg := goals.head! let g := mvars.filterReachable goals let mut vertices := #[] let mut edges := #[] let mut maxLabelRadius := 0.0 for (m, ns) in g do -- TODO: mark delayed assigned mvars in yet another colour? let vAssigned ← m.isAssignedOrDelayedAssigned let (w, h, label) ← mkLabel m (stroke := if m == mg then "var(--vscode-lean4-infoView\\.turnstile)" else if vAssigned then "var(--vscode-editor-foreground)" else "var(--vscode-lean4-infoView\\.caseLabel)") (fill := if vAssigned then "var(--vscode-editorHoverWidget-background)" else "var(--vscode-editor-background)") maxLabelRadius := max maxLabelRadius (Float.sqrt <| (w.toFloat/2)^2 + (h.toFloat/2)^2) let val? ← (← getMCtx).eAssignment.find? m |>.mapM fun v => return <span className="font-code"> {.text s!"?{← m.getName}"} := <InteractiveCode fmt={← m.withContext <| Widget.ppExprTagged v} /> </span> let delayedVal? ← (← getMCtx).dAssignment.find? m |>.mapM fun n => return <span className="font-code"> {.text s!"?{← m.getName}"} [delayed] := {.text s!"?{← n.mvarIdPending.getName}"} </span> vertices := vertices.push { id := toString m.name label boundingShape := .rect w.toFloat h.toFloat details? := val? <|> delayedVal? } for (n, b) in ns do if b then edges := edges.push { source := toString m.name target := toString n.name } else edges := edges.push { source := toString m.name target := toString n.name attrs := #[("strokeDasharray", "5,5")] } return <GraphDisplay vertices={vertices} edges={edges} forces={#[ .link { distance? := some (maxLabelRadius * 3) }, .manyBody { strength? := some (-150) }, .x { strength? := some 0.01 }, .y { strength? := some 0.01 } ]} showDetails={true} /> open Server ProofWidgets Jsx @[server_rpc_method] def MVarGraph.rpc (props : PanelWidgetProps) : RequestM (RequestTask Html) := RequestM.asTask do let inner : Html ← (do -- Are there any goals unsolved? If so, the first one is the current main goal. if props.goals.isEmpty then return <span>No goals.</span> let some g := props.goals[0]? | unreachable! -- Execute the next part using the metavariable context and local context of the main goal. g.ctx.val.runMetaM {} do let md ← g.mvarId.getDecl let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)} Meta.withLCtx lctx md.localInstances do drawMVarGraph <| props.goals.toList.map (·.mvarId)) return <details «open»={true}> <summary className="mv2 pointer">Metavariable graph</summary> <div className="ml1">{inner}</div> </details> @[widget_module] def MVarGraph : Component ProofWidgets.PanelWidgetProps := mk_rpc_widget% MVarGraph.rpc show_panel_widgets [local MVarGraph] -- When printing an assigned metavariable `?m := v`, -- print out the metavariable name `?m` rather than `v`. set_option pp.instantiateMVars false -- Do the same for delayed assigned metavariables. set_option pp.mvars.delayed true example {P Q : Prop} (p : P) (q : Q) : P ∧ Q := by constructor . exact p . exact q example {P Q R : Prop} (p : P) (q : Q) (r : R) : (P ∧ Q) ∧ R := by constructor constructor . exact p . exact q . exact r example {P Q R : Prop} (pq : P → Q) (qr : Q → R) : P → R := by intro p apply qr apply pq exact p example {α : Type} {P Q : α → Prop} (pq : ∀ x, P x → Q x) (px : ∀ x, P x) : ∀ x, Q x := by intro y apply pq apply px example {α : Type} {P : α → Prop} {a : α} (pa : P a) : ∃ x, P x := by refine ⟨?w, ?h⟩ exact a exact pa example {α : Type} {P : α → Prop} {a b c : α} (ab : a = b) (bc : b = c) (pa : P a) : P c := by rw [← bc] rw [← ab] exact pa example (n : Nat) : n = 0 ∨ ∃ m, n = m + 1 := by induction n -- a big mess . exact Or.inl rfl . exact Or.inr ⟨_, rfl⟩
.lake/packages/proofwidgets/ProofWidgets/Demos/Graph/ExprGraph.lean
module public meta import ProofWidgets.Component.GraphDisplay public meta import ProofWidgets.Component.HtmlDisplay public meta import Lean.Util.FoldConsts public meta section open ProofWidgets Jsx /-- Display the graph of all constants appearing in a given constant. -/ syntax (name := exprGraphCmd) "#expr_graph" ident : command open Lean Elab Command in @[command_elab exprGraphCmd] def elabExprGraphCmd : CommandElab := fun | stx@`(#expr_graph $i:ident) => runTermElabM fun _ => do let env ← getEnv let c ← realizeGlobalConstNoOverloadWithInfo i let some c := env.find? c | throwError "internal error" let nodes : NameSet := c.getUsedConstantsAsSet let mut edges : Std.HashSet (String × String) := {} for a in nodes do for b in nodes do let some bb := env.find? b | continue if bb.getUsedConstantsAsSet.contains a then edges := edges.insert (toString a, toString b) let mut nodesWithInfos : Array GraphDisplay.Vertex := #[] let mut maxRadius := 10 for node in nodes.toArray do let some c := env.find? node | continue let doc? ← findDocString? env node let ee ← Lean.Widget.ppExprTagged c.type let us ← Meta.mkFreshLevelMVarsFor c let e ← Lean.Widget.ppExprTagged (.const node us) let node := toString node let rx := node.length * 3 maxRadius := Nat.max maxRadius rx let newNode : GraphDisplay.Vertex := { id := node label := <g> <ellipse fill="var(--vscode-editor-background)" stroke="var(--vscode-editorHoverWidget-border)" rx={(rx*2 : Nat)} ry="10" /> <text x={s!"-{rx}"} y="5" className="font-code">{.text node}</text> </g> boundingShape := .rect (rx*4).toFloat 20 details? := match doc? with | some d => <div> <InteractiveCode fmt={e} />{.text " : "}<InteractiveCode fmt={ee} /> <MarkdownDisplay contents={d} /> </div> | none => <span> <InteractiveCode fmt={e} />{.text " : "}<InteractiveCode fmt={ee} /> </span> } nodesWithInfos := nodesWithInfos.push newNode let html : Html := <GraphDisplay vertices={nodesWithInfos} edges={edges.fold (init := #[]) fun acc (a,b) => acc.push {source := a, target := b}} forces={#[ .link { distance? := Float.ofNat (maxRadius * 2) }, .collide { radius? := Float.ofNat maxRadius }, .x { strength? := some 0.05 }, .y { strength? := some 0.05 } ]} showDetails={true} /> Widget.savePanelWidgetInfo (hash HtmlDisplayPanel.javascript) (return json% { html : $(← Server.rpcEncode html) }) stx | stx => throwError "Unexpected syntax {stx}" def a : Nat := 0 def b : Nat := 1 def foo (c : Nat) : Nat × Int := (a + b * c, a / b) -- Put your cursor here. #expr_graph foo
.lake/packages/proofwidgets/ProofWidgets/Presentation/Expr.lean
module public meta import ProofWidgets.Data.Html public meta section namespace ProofWidgets open Lean Server /-- An `Expr` presenter is similar to a delaborator but outputs HTML trees instead of syntax, and the output HTML can contain elements which interact with the original `Expr` in some way. We call interactive outputs with a reference to the original input *presentations*. -/ structure ExprPresenter where /-- A user-friendly name for this presenter. For example, "LaTeX". -/ userName : String /-- Whether the output HTML has inline (think something which fits in the space normally occupied by an `Expr`, e.g. LaTeX) or block (think large diagram which needs dedicated space) layout. -/ layoutKind : LayoutKind := .block present : Expr → MetaM Html /-- Register an Expr presenter. It must have the type `ProofWidgets.ExprPresenter`. -/ initialize exprPresenters : TagAttribute ← registerTagAttribute `expr_presenter "Register an Expr presenter. It must have the type `ProofWidgets.ExprPresenter`." (validate := fun nm => do let const ← getConstInfo nm if !const.type.isConstOf ``ExprPresenter then throwError m!"type mismatch, expected {mkConst ``ExprPresenter} but got {const.type}" return ()) private unsafe def evalExprPresenterUnsafe (env : Environment) (opts : Options) (constName : Name) : Except String ExprPresenter := env.evalConstCheck ExprPresenter opts ``ExprPresenter constName @[implemented_by evalExprPresenterUnsafe] opaque evalExprPresenter (env : Environment) (opts : Options) (constName : Name) : Except String ExprPresenter structure GetExprPresentationsParams where expr : WithRpcRef ExprWithCtx deriving RpcEncodable structure ExprPresentationData where name : Name userName : String html : Html deriving RpcEncodable structure ExprPresentations where presentations : Array ExprPresentationData deriving RpcEncodable @[server_rpc_method] def getExprPresentations : GetExprPresentationsParams → RequestM (RequestTask ExprPresentations) | ⟨ref⟩ => RequestM.asTask do let mut presentations : Array ExprPresentationData := #[] let expr := ref.val let env := expr.ci.env for nm in exprPresenters.ext.getState env do presentations ← addPresenterIfApplicable expr nm presentations -- FIXME: The fact that we need this loop suggests that TagAttribute is not the right way -- to implement a persistent, iterable set of names. for modNm in env.allImportedModuleNames do let some modIdx := env.getModuleIdx? modNm | throw <| RequestError.internalError s!"unknown module {modNm}" for nm in exprPresenters.ext.getModuleEntries env modIdx do presentations ← addPresenterIfApplicable expr nm presentations return { presentations } where addPresenterIfApplicable (expr : ExprWithCtx) (nm : Name) (ps : Array ExprPresentationData) : RequestM (Array ExprPresentationData) := match evalExprPresenter expr.ci.env expr.ci.options nm with | .ok p => try let html ← expr.runMetaM fun e => do let e ← Lean.instantiateMVars e p.present e return ps.push ⟨nm, p.userName, html⟩ catch _ => return ps | .error e => throw <| RequestError.internalError s!"Failed to evaluate Expr presenter '{nm}': {e}" structure GetExprPresentationParams where expr : WithRpcRef ExprWithCtx /-- Name of the presenter to use. -/ name : Name deriving RpcEncodable structure ExprPresentationProps where expr : WithRpcRef ExprWithCtx deriving RpcEncodable /-- This component shows a selection of all known and applicable `ProofWidgets.ExprPresenter`s which are used to render the expression when selected. The one with highest precedence (TODO) is shown by default. -/ @[widget_module] def ExprPresentation : Component ExprPresentationProps where javascript := include_str ".." / ".." / ".lake" / "build" / "js" / "exprPresentation.js" end ProofWidgets
.lake/packages/batteries/README.md
# Batteries The "batteries included" extended library for Lean 4. This is a collection of data structures and tactics intended for use by both computer-science applications and mathematics applications of Lean 4. # Using `batteries` To use `batteries` in your project, add the following to your `lakefile.lean`: ```lean require "leanprover-community" / "batteries" @ git "main" ``` Or add the following to your `lakefile.toml`: ```toml [[require]] name = "batteries" scope = "leanprover-community" rev = "main" ``` Additionally, please make sure that you're using the version of Lean that the current version of `batteries` expects. The easiest way to do this is to copy the [`lean-toolchain`](./lean-toolchain) file from this repository to your project. Once you've added the dependency declaration, the command `lake update` checks out the current version of `batteries` and writes it the Lake manifest file. Don't run this command again unless you're prepared to potentially also update your Lean compiler version, as it will retrieve the latest version of dependencies and add them to the manifest. # Build instructions * Get the newest version of `elan`. If you already have installed a version of Lean, you can run ```sh elan self update ``` If the above command fails, or if you need to install `elan`, run ```sh curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh ``` If this also fails, follow the instructions under `Regular install` [here](https://leanprover-community.github.io/get_started.html). * To build `batteries` run `lake build`. * To build and run all tests, run `lake test`. * To run the environment linter, run `lake lint`. * If you added a new file, run the command `scripts/updateBatteries.sh` to update the imports. # Documentation You can generate `batteries` documentation with ```sh cd docs lake build Batteries:docs ``` The top-level HTML file will be located at `docs/doc/index.html`, though to actually expose the documentation you need to run an HTTP server (e.g. `python3 -m http.server`) in the `docs/doc` directory. Note that documentation for the latest nightly of `batteries` is also available as part of [the Mathlib 4 documentation][mathlib4 docs]. [mathlib4 docs]: https://leanprover-community.github.io/mathlib4_docs/Batteries.html # Contributing The first step to contribute is to create a fork of Batteries. Then add your contributions to a branch of your fork and make a PR to Batteries. Do not make your changes to the main branch of your fork, that may lead to complications on your end. Every pull request should have exactly one of the status labels `awaiting-review`, `awaiting-author` or `WIP` (in progress). To change the status label of a pull request, add a comment containing one of these options and _nothing else_. This will remove the previous label and replace it by the requested status label. These labels are used for triage. One of the easiest ways to contribute is to find a missing proof and complete it. The [`proof_wanted`](https://github.com/search?q=repo%3Aleanprover-community%2Fbatteries+language%3ALean+%2F^proof_wanted%2F&type=code) declaration documents statements that have been identified as being useful, but that have not yet been proven. ### Mathlib Adaptations Batteries PRs often affect Mathlib, a key component of the Lean ecosystem. When Batteries changes in a significant way, Mathlib must adapt promptly. When necessary, Batteries contributors are expected to either create an adaptation PR on Mathlib, or ask for assistance for and to collaborate with this necessary process. Every Batteries PR has an automatically created [Mathlib Nightly Testing](https://github.com/leanprover-community/mathlib4-nightly-testing/) branch called `batteries-pr-testing-N` where `N` is the number of the Batteries PR. This is a clone of Mathlib where the Batteries requirement points to the Batteries PR branch instead of the main branch. Batteries uses this branch to check whether the Batteries PR needs Mathlib adaptations. A tag `builds-mathlib` will be issued when this branch needs no adaptation; a tag `breaks-mathlib` will be issued when the branch does need an adaptation. The first step in creating an adaptation PR is to switch to the `batteries-pr-testing-N` branch and push changes to that branch until the Mathlib CI process works. You may need to ask for write access to [Mathlib Nightly Testing](https://github.com/leanprover-community/mathlib4-nightly-testing/) to do that. Changes to the Batteries PR will be integrated automatically as you work on this process. Do not redirect the Batteries requirement to main until the Batteries PR is merged. Please ask questions to Batteries and Mathlib maintainers if you run into issues with this process. When everything works, create an adaptation PR on Mathlib from the `batteries-pr-testing-N` branch. You may need to ping a Mathlib maintainer to review the PR, ask if you don't know who to ping. Once the Mathlib adaptation PR and the original Batteries PR have been reviewed and accepted, the Batteries PR will be merged first. Then, the Mathlib PR's lakefile needs to be repointed to the Batteries main branch: change the Batteries line to ```lean require "leanprover-community" / "batteries" @ git "main" ``` Once CI once again checks out on Mathlib, the adaptation PR can be merged using the regular Mathlib process.
.lake/packages/batteries/Batteries.lean
module public import Batteries.Classes.Cast public import Batteries.Classes.Deprecated public import Batteries.Classes.Order public import Batteries.Classes.RatCast public import Batteries.Classes.SatisfiesM public import Batteries.CodeAction public import Batteries.CodeAction.Attr public import Batteries.CodeAction.Basic public import Batteries.CodeAction.Deprecated public import Batteries.CodeAction.Match public import Batteries.CodeAction.Misc public import Batteries.Control.AlternativeMonad public import Batteries.Control.ForInStep public import Batteries.Control.ForInStep.Basic public import Batteries.Control.ForInStep.Lemmas public import Batteries.Control.LawfulMonadState public import Batteries.Control.Lemmas public import Batteries.Control.Monad public import Batteries.Control.Nondet.Basic public import Batteries.Control.OptionT public import Batteries.Data.Array public import Batteries.Data.AssocList public import Batteries.Data.BinaryHeap public import Batteries.Data.BinomialHeap public import Batteries.Data.BitVec public import Batteries.Data.ByteArray public import Batteries.Data.ByteSlice public import Batteries.Data.Char public import Batteries.Data.DList public import Batteries.Data.Fin public import Batteries.Data.FloatArray public import Batteries.Data.HashMap public import Batteries.Data.Int public import Batteries.Data.List public import Batteries.Data.MLList public import Batteries.Data.NameSet public import Batteries.Data.Nat public import Batteries.Data.PairingHeap public import Batteries.Data.RBMap public import Batteries.Data.Random public import Batteries.Data.Range public import Batteries.Data.Rat public import Batteries.Data.Stream public import Batteries.Data.String public import Batteries.Data.UInt public import Batteries.Data.UnionFind public import Batteries.Data.Vector public import Batteries.Lean.AttributeExtra public import Batteries.Lean.EStateM public import Batteries.Lean.Except public import Batteries.Lean.Expr public import Batteries.Lean.Float public import Batteries.Lean.HashMap public import Batteries.Lean.HashSet public import Batteries.Lean.IO.Process public import Batteries.Lean.Json public import Batteries.Lean.LawfulMonad public import Batteries.Lean.LawfulMonadLift public import Batteries.Lean.Meta.Basic public import Batteries.Lean.Meta.DiscrTree public import Batteries.Lean.Meta.Expr public import Batteries.Lean.Meta.Inaccessible public import Batteries.Lean.Meta.InstantiateMVars public import Batteries.Lean.Meta.SavedState public import Batteries.Lean.Meta.Simp public import Batteries.Lean.Meta.UnusedNames public import Batteries.Lean.MonadBacktrack public import Batteries.Lean.NameMapAttribute public import Batteries.Lean.PersistentHashMap public import Batteries.Lean.PersistentHashSet public import Batteries.Lean.Position public import Batteries.Lean.SatisfiesM public import Batteries.Lean.Syntax public import Batteries.Lean.System.IO public import Batteries.Lean.TagAttribute public import Batteries.Lean.Util.EnvSearch public import Batteries.Linter public import Batteries.Linter.UnnecessarySeqFocus public import Batteries.Linter.UnreachableTactic public import Batteries.Logic public import Batteries.Tactic.Alias public import Batteries.Tactic.Basic public import Batteries.Tactic.Case public import Batteries.Tactic.Congr public import Batteries.Tactic.Exact public import Batteries.Tactic.GeneralizeProofs public import Batteries.Tactic.HelpCmd public import Batteries.Tactic.Init public import Batteries.Tactic.Instances public import Batteries.Tactic.Lemma public import Batteries.Tactic.Lint public import Batteries.Tactic.Lint.Basic public import Batteries.Tactic.Lint.Frontend public import Batteries.Tactic.Lint.Misc public import Batteries.Tactic.Lint.Simp public import Batteries.Tactic.Lint.TypeClass public import Batteries.Tactic.NoMatch public import Batteries.Tactic.OpenPrivate public import Batteries.Tactic.PermuteGoals public import Batteries.Tactic.PrintDependents public import Batteries.Tactic.PrintOpaques public import Batteries.Tactic.PrintPrefix public import Batteries.Tactic.SeqFocus public import Batteries.Tactic.ShowUnused public import Batteries.Tactic.SqueezeScope public import Batteries.Tactic.Trans public import Batteries.Tactic.Unreachable public import Batteries.Util.Cache public import Batteries.Util.ExtendedBinder public import Batteries.Util.LibraryNote public import Batteries.Util.Panic public import Batteries.Util.Pickle public import Batteries.Util.ProofWanted public import Batteries.WF
.lake/packages/batteries/Shake/Main.lean
import Lake.CLI.Main /-! # `lake exe shake` command This command will check the current project (or a specified target module) and all dependencies for unused imports. This works by looking at generated `.olean` files to deduce required imports and ensuring that every import is used to contribute some constant. Because recompilation is not needed this is quite fast (about 8 seconds to check `Mathlib` and all dependencies), but it has some known limitations: * Tactics that are used during elaboration generally leave no trace in the proof term, so they will be incorrectly marked as unused. * Similarly, files that contribute only notations will not be detected. * Conversely, files that define tactics and notations are also likely to have false positives because the notation itself does not depend on the referenced constant (it elaborates to a name literal rather than an actual reference to the target constant). To mitigate this, the `scripts/noshake.json` file is used to suppress known false positives. See `ShakeCfg` for information regarding the file format. -/ /-- help string for the command line interface -/ def help : String := "Lean project tree shaking tool Usage: lake exe shake [OPTIONS] <MODULE>.. Arguments: <MODULE> A module path like `Mathlib`. All files transitively reachable from the provided module(s) will be checked. Options: --force Skips the `lake build --no-build` sanity check --fix Apply the suggested fixes directly. Make sure you have a clean checkout before running this, so you can review the changes. --cfg <FILE> (default: scripts/noshake.json) Use FILE to specify which imports we should ignore. --update Assume that all issues we find are false positives and update the config file to include them. --no-downstream Unless disabled, shake will check downstream files that were transitively depending on the import we want to remove and re-add the import to these downstream files. # The noshake.json file The file passed in the --cfg argument is a JSON file with the following structure: { \"ignoreAll\": [NAME], \"ignoreImport\": [NAME], \"ignore\": {NAME: [NAME]} } The fields can be omitted if empty. They have the following interpretation: * ignoreAll: All imports in these files should be treated as necessary * ignore[X]: All imports in the list should be treated as necessary when processing X * ignoreImport: These files should be treated as necessary when imported into any other file. " open Lean /-- We use `Nat` as a bitset for doing efficient set operations. The bit indexes will usually be a module index. -/ abbrev Bitset := Nat /-- The main state of the checker, containing information on all loaded modules. -/ structure State where /-- Maps a module name to its index in the module list. -/ toIdx : Std.HashMap Name USize := {} /-- Maps a module index to the module name. -/ modNames : Array Name := #[] /-- Maps a module index to the module data. -/ mods : Array ModuleData := #[] /-- `j ∈ deps[i]` if module `j` is a direct dependency of module `i` -/ deps : Array (Array USize) := #[] /-- `j ∈ transDeps[i]` is the reflexive transitive closure of `deps` -/ transDeps : Array Bitset := #[] /-- `j ∈ needs[i]` if module `i` uses a constant declared in module `j`. Note: this is left empty if `args.downstream` is false, we calculate `needs` on demand -/ needs : Array Bitset := #[] /-- Maps a constant name to the module index containing it. A value of `none` means the constant was found in multiple modules, in which case we do not track it. -/ constToIdx : Std.HashMap Name (Option USize) := {} /-- Returns `true` if this is a constant whose body should not be considered for dependency tracking purposes. -/ def isBlacklisted (name : Name) : Bool := -- Compiler-produced definitions are skipped, because they can sometimes pick up spurious -- dependencies due to specializations in unrelated files. Even if we remove these modules -- from the import path, the compiler will still just find another way to compile the definition. if let .str _ "_cstage2" := name then true else if let .str _ "_cstage1" := name then true else false /-- Calculates the value of the `needs[i]` bitset for a given module `mod`. Bit `j` is set in the result if some constant from module `j` is used in this module. -/ def calcNeeds (constToIdx : Std.HashMap Name (Option USize)) (mod : ModuleData) : Bitset := mod.constants.foldl (init := 0) fun deps ci => if isBlacklisted ci.name then deps else let deps := visitExpr ci.type deps match ci.value? with | some e => visitExpr e deps | none => deps where /-- Accumulate the results from expression `e` into `deps`. -/ visitExpr e deps := Lean.Expr.foldConsts e deps fun c deps => match constToIdx[c]? with | some (some i) => deps ||| (1 <<< i.toNat) | _ => deps /-- Calculates the same as `calcNeeds` but tracing each module to a specific constant. -/ def getExplanations (constToIdx : Std.HashMap Name (Option USize)) (mod : ModuleData) : Std.HashMap USize (Name × Name) := mod.constants.foldl (init := {}) fun deps ci => if isBlacklisted ci.name then deps else let deps := visitExpr ci.name ci.type deps match ci.value? with | some e => visitExpr ci.name e deps | none => deps where /-- Accumulate the results from expression `e` into `deps`. -/ visitExpr name e deps := Lean.Expr.foldConsts e deps fun c deps => match constToIdx[c]? with | some (some i) => if if let some (name', _) := deps[i]? then decide (name.toString.length < name'.toString.length) else true then deps.insert i (name, c) else deps | _ => deps /-- Load all the modules in `imports` into the `State`, as well as their transitive dependencies. Returns a pair `(imps, transImps)` where: * `j ∈ imps` if `j` is one of the module indexes in `imports` * `j ∈ transImps` if module `j` is transitively reachable from `imports` -/ partial def loadModules (imports : Array Import) : StateT State IO (Array USize × Bitset) := do let mut imps := #[] let mut transImps := 0 for imp in imports do let s ← get if let some i := s.toIdx[imp.module]? then imps := imps.push i transImps := transImps ||| s.transDeps[i]! else let mFile ← findOLean imp.module unless (← mFile.pathExists) do throw <| IO.userError s!"object file '{mFile}' of module {imp.module} does not exist" let (mod, _) ← readModuleData mFile let (deps, transDeps) ← loadModules mod.imports let s ← get let n := s.mods.size.toUSize let transDeps := transDeps ||| (1 <<< n.toNat) imps := imps.push n transImps := transImps ||| transDeps set (σ := State) { toIdx := s.toIdx.insert imp.module n modNames := s.modNames.push imp.module mods := s.mods.push mod deps := s.deps.push deps transDeps := s.transDeps.push transDeps needs := s.needs constToIdx := mod.constNames.foldl (init := s.constToIdx) fun m a => match m.getThenInsertIfNew? a n with | (some (some _), m) => -- Note: If a constant is found in multiple modules, we assume it is an auto-generated -- definition which is created on demand, and therefore it is safe to ignore any -- dependencies via this definition because it will just be re-created in the current -- module if we don't import it. m.insert a none | (_, m) => m } return (imps, transImps) /-- The list of edits that will be applied in `--fix`. `edits[i] = (removed, added)` where: * If `j ∈ removed` then we want to delete module named `j` from the imports of `i` * If `j ∈ added` then we want to add module index `j` to the imports of `i`. We keep this as a bitset because we will do transitive reduction before applying it -/ abbrev Edits := Std.HashMap Name (NameSet × Bitset) /-- Register that we want to remove `tgt` from the imports of `src`. -/ def Edits.remove (ed : Edits) (src tgt : Name) : Edits := match ed.get? src with | none => ed.insert src (NameSet.insert ∅ tgt, 0) | some (a, b) => ed.insert src (a.insert tgt, b) /-- Register that we want to add `tgt` to the imports of `src`. -/ def Edits.add (ed : Edits) (src : Name) (tgt : Nat) : Edits := match ed.get? src with | none => ed.insert src (∅, 1 <<< tgt) | some (a, b) => ed.insert src (a, b ||| (1 <<< tgt)) /-- Parse a source file to extract the location of the import lines, for edits and error messages. Returns `(path, inputCtx, imports, endPos)` where `imports` is the `Lean.Parser.Module.import` list and `endPos` is the position of the end of the header. -/ def parseHeaderFromString (text path : String) : IO (System.FilePath × Parser.InputContext × TSyntaxArray ``Parser.Module.import × String.Pos.Raw) := do let inputCtx := Parser.mkInputContext text path let (header, parserState, msgs) ← Parser.parseHeader inputCtx if !msgs.toList.isEmpty then -- skip this file if there are parse errors msgs.forM fun msg => msg.toString >>= IO.println throw <| .userError "parse errors in file" -- the insertion point for `add` is the first newline after the imports let insertion := header.raw.getTailPos?.getD parserState.pos let insertion := text.findAux (· == '\n') text.endPos insertion |>.increaseBy 1 pure (path, inputCtx, .mk header.raw[2].getArgs, insertion) /-- Parse a source file to extract the location of the import lines, for edits and error messages. Returns `(path, inputCtx, imports, endPos)` where `imports` is the `Lean.Parser.Module.import` list and `endPos` is the position of the end of the header. -/ def parseHeader (srcSearchPath : SearchPath) (mod : Name) : IO (System.FilePath × Parser.InputContext × TSyntaxArray ``Parser.Module.import × String.Pos.Raw) := do -- Parse the input file let some path ← srcSearchPath.findModuleWithExt "lean" mod | throw <| .userError "error: failed to find source file for {mod}" let text ← IO.FS.readFile path parseHeaderFromString text path.toString /-- Gets the name `Foo` in `import Foo`. -/ def importId : TSyntax ``Parser.Module.import → Name | `(Parser.Module.import| import $id) => id.getId | stx => panic! s!"unexpected syntax {stx}" /-- Analyze and report issues from module `i`. Arguments: * `s`: The main state (contains all the modules and dependency information) * `srcSearchPath`: Used to find the path for error reporting purposes * `ignoreImps`: if `j ∈ ignoreImps` then it will be treated as used * `i`: the module index * `needs`: this is the same as `s.needs[i]`, except that this array may not be initialized if `downstream` mode is disabled so we pass it in here * `edits`: accumulates the list of edits to apply if `--fix` is true * `downstream`: if true, then we report downstream files that need to be fixed too -/ def visitModule (s : State) (srcSearchPath : SearchPath) (ignoreImps : Bitset) (i : Nat) (needs : Bitset) (edits : Edits) (downstream := true) (githubStyle := false) (explain := false) : IO Edits := do -- Do transitive reduction of `needs` in `deps` and transitive closure in `transDeps`. -- Include the `ignoreImps` in `transDeps` let mut deps := needs let mut transDeps := needs ||| ignoreImps for j in [0:s.mods.size] do if deps &&& (1 <<< j) != 0 then let deps2 := s.transDeps[j]! deps := deps ^^^ (deps &&& deps2) ^^^ (1 <<< j) transDeps := transDeps ||| deps2 -- Any import which is not in `transDeps` was unused. -- Also accumulate `newDeps` which is the transitive closure of the remaining imports let mut toRemove := #[] let mut newDeps := 0 for imp in s.mods[i]!.imports do let j := s.toIdx[imp.module]! if transDeps &&& (1 <<< j.toNat) == 0 then toRemove := toRemove.push j else newDeps := newDeps ||| s.transDeps[j]! if toRemove.isEmpty then return edits -- nothing to do -- If `newDeps` does not cover `needs`, then we have to add back some imports until it does. -- To minimize new imports we pick only new imports which are not transitively implied by -- another new import let mut toAdd := #[] for j in [0:s.mods.size] do if deps &&& (1 <<< j) != 0 && newDeps &&& (1 <<< j) == 0 then toAdd := toAdd.push j newDeps := newDeps ||| s.transDeps[j]! -- mark and report the removals let mut edits := toRemove.foldl (init := edits) fun edits n => edits.remove s.modNames[i]! s.modNames[n]! if githubStyle then try let (path, inputCtx, imports, endHeader) ← parseHeader srcSearchPath s.modNames[i]! for stx in imports do if toRemove.any fun i => s.modNames[i]! == importId stx then let pos := inputCtx.fileMap.toPosition stx.raw.getPos?.get! println! "{path}:{pos.line}:{pos.column+1}: warning: unused import \ (use `lake exe shake --fix` to fix this, or `lake exe shake --update` to ignore)" if !toAdd.isEmpty then -- we put the insert message on the beginning of the last import line let pos := inputCtx.fileMap.toPosition endHeader println! "{path}:{pos.line-1}:1: warning: \ import {toAdd.map (s.modNames[·]!)} instead" catch _ => pure () if let some path ← srcSearchPath.findModuleWithExt "lean" s.modNames[i]! then println! "{path}:" else println! "{s.modNames[i]!}:" println! " remove {toRemove.map (s.modNames[·]!)}" -- mark and report the additions if !toAdd.isEmpty then edits := toAdd.foldl (init := edits) fun edits n => edits.add s.modNames[i]! n println! " add {toAdd.map (s.modNames[·]!)}" if downstream && !toRemove.isEmpty then -- In `downstream` mode, we should also check all the other modules to find out if -- we have a situation like `A -> B -/> C -> D`, where we are removing the `B -> C` import -- but `D` depends on `A` and only directly imports `C`. -- This situation occurs when `A ∈ needs[D]`, `C ∈ transDeps[D]`, and `A ∉ newTransDeps[D]`, -- where `newTransDeps` is the result of recalculating `transDeps` after breaking the `B -> C` -- link. -- calculate `newTransDeps[C]`, removing all `B -> C` links from `toRemove` and adding `toAdd` let mut newTransDepsI := 1 <<< i for j in s.deps[i]! do if !toRemove.contains j then newTransDepsI := newTransDepsI ||| s.transDeps[j]! for j in toAdd do newTransDepsI := newTransDepsI ||| s.transDeps[j]! let mut newTransDeps := s.transDeps.set! i newTransDepsI -- deep copy let mut reAdded := #[] for j in [i+1:s.mods.size] do -- for each module `D` if s.transDeps[j]! &&& (1 <<< i) != 0 then -- which imports `C` -- calculate `newTransDeps[D]` assuming no change to the imports of `D` let mut newTransDepsJ := s.deps[j]!.foldl (init := 1 <<< j) fun d k => d ||| newTransDeps[k]! let diff := s.transDeps[j]! ^^^ newTransDepsJ if diff != 0 then -- if the dependency closure of `D` changed let mut reAdd := diff &&& s.needs[j]! if reAdd != 0 then -- and there are things from `needs[D]` which were lost: -- Add them back. -- `reAdd` is the set of all files `A` which have to be added back -- to the closure of `D`, but some of them might be importing others, -- so we take the transitive reduction of `reAdd`. let mut reAddArr := [] let mut k := j while reAdd != 0 do -- note: this loop terminates because `reAdd ⊆ [0:k]` k := k - 1 if reAdd &&& (1 <<< k) != 0 then reAddArr := k :: reAddArr reAdd := reAdd ^^^ (reAdd &&& newTransDeps[k]!) -- add these to `newTransDeps[D]` so that files downstream of `D` -- (later in the `for j` loop) will take this into account newTransDepsJ := newTransDepsJ ||| newTransDeps[k]! edits := reAddArr.foldl (init := edits) (·.add s.modNames[j]! ·) reAdded := reAdded.push (j, reAddArr) newTransDeps := newTransDeps.set! j newTransDepsJ if !reAdded.isEmpty then println! " instead" for (j, reAddArr) in reAdded do println! " import {reAddArr.map (s.modNames[·]!)} in {s.modNames[j]!}" if explain then let explanation := getExplanations s.constToIdx s.mods[i]! let sanitize n := if n.hasMacroScopes then (sanitizeName n).run' { options := {} } else n let run (j : USize) := do if let some (n, c) := explanation[j]? then println! " note: {s.modNames[i]!} requires {s.modNames[j]!}\ \n because {sanitize n} refers to {sanitize c}" for imp in s.mods[i]!.imports do run <| s.toIdx[imp.module]! for i in toAdd do run i.toUSize return edits /-- Convert a list of module names to a bitset of module indexes -/ def toBitset (s : State) (ns : List Name) : Bitset := ns.foldl (init := 0) fun c name => match s.toIdx[name]? with | some i => c ||| (1 <<< i.toNat) | none => c /-- The parsed CLI arguments. See `help` for more information -/ structure Args where /-- `--help`: shows the help -/ help : Bool := false /-- `--force`: skips the `lake build --no-build` sanity check -/ force : Bool := false /-- `--no-downstream`: disables downstream mode -/ downstream : Bool := true /-- `--gh-style`: output messages that can be parsed by `gh-problem-matcher-wrap` -/ githubStyle : Bool := false /-- `--explain`: give constants explaining why each module is needed -/ explain : Bool := false /-- `--fix`: apply the fixes directly -/ fix : Bool := false /-- `--update`: update the config file -/ update : Bool := false /-- `--global`: with `--update`, add imports to `ignoreImport` instead of `ignore` -/ global : Bool := false /-- `--cfg FILE`: choose a custom location for the config file -/ cfg : Option String := none /-- `<MODULE>..`: the list of root modules to check -/ mods : Array Name := #[] instance {α} [FromJson α] : FromJson (NameMap α) where fromJson? j := do (← j.getObj?).foldlM (init := mkNameMap _) fun m a b => do m.insert a.toName <$> fromJson? b instance {α} [ToJson α] : ToJson (NameMap α) where toJson m := Json.obj <| m.foldl (init := ∅) fun m a b => m.insert (toString a) (toJson b) /-- The config file format, which we both read and write. -/ structure ShakeCfg where /-- All imports from modules in this list will be ignored -/ ignoreAll? : Option (List Name) := none /-- The modules in this list will be ignored as imports of any other file -/ ignoreImport? : Option (List Name) := [`Init, `Lean] /-- If `X` maps to `Y` then an import of `Y` in module `X` will be ignored -/ ignore? : Option (NameMap (Array Name)) := none deriving FromJson, ToJson /-- The main entry point. See `help` for more information on arguments. -/ def main (args : List String) : IO UInt32 := do initSearchPath (← findSysroot) -- Parse the arguments let rec parseArgs (args : Args) : List String → Args | [] => args | "--help" :: rest => parseArgs { args with help := true } rest | "--force" :: rest => parseArgs { args with force := true } rest | "--no-downstream" :: rest => parseArgs { args with downstream := false } rest | "--fix" :: rest => parseArgs { args with fix := true } rest | "--explain" :: rest => parseArgs { args with explain := true } rest | "--gh-style" :: rest => parseArgs { args with githubStyle := true } rest | "--update" :: rest => parseArgs { args with update := true } rest | "--global" :: rest => parseArgs { args with global := true } rest | "--cfg" :: cfg :: rest => parseArgs { args with cfg := cfg } rest | "--" :: rest => { args with mods := args.mods ++ rest.map (·.toName) } | other :: rest => parseArgs { args with mods := args.mods.push other.toName } rest let args := parseArgs {} args -- Bail if `--help` is passed if args.help then IO.println help IO.Process.exit 0 if !args.force then if (← IO.Process.output { cmd := "lake", args := #["build", "--no-build"] }).exitCode != 0 then IO.println "There are out of date oleans. Run `lake build` or `lake exe cache get` first" IO.Process.exit 1 -- Determine default module(s) to run shake on let defaultTargetModules : Array Name ← try let (elanInstall?, leanInstall?, lakeInstall?) ← Lake.findInstall? let config ← Lake.MonadError.runEIO <| Lake.mkLoadConfig { elanInstall?, leanInstall?, lakeInstall? } let some workspace ← Lake.loadWorkspace config |>.toBaseIO | throw <| IO.userError "failed to load Lake workspace" let defaultTargetModules := workspace.root.defaultTargets.flatMap fun target => if let some lib := workspace.root.findLeanLib? target then lib.roots else if let some exe := workspace.root.findLeanExe? target then #[exe.config.root] else #[] pure defaultTargetModules catch _ => pure #[] -- Parse the `--cfg` argument let srcSearchPath ← getSrcSearchPath let cfgFile ← if let some cfg := args.cfg then pure (some ⟨cfg⟩) else if let some mod := defaultTargetModules[0]? then if let some path ← srcSearchPath.findModuleWithExt "lean" mod then pure (some (path.parent.get! / "scripts" / "noshake.json")) else pure none else pure none -- Read the config file -- `isValidCfgFile` is `false` if and only if the config file is present and invalid. let (cfg, isValidCfgFile) ← if let some file := cfgFile then try pure (← IO.ofExcept (Json.parse (← IO.FS.readFile file) >>= fromJson? (α := ShakeCfg)), true) catch e => -- The `cfgFile` is invalid, so we print the error and return `isValidCfgFile = false`. println! "{e.toString}" pure ({}, false) else pure ({}, true) if !isValidCfgFile then IO.println s!"Invalid config file '{cfgFile.get!}'" IO.Process.exit 1 else -- the list of root modules let mods := if args.mods.isEmpty then defaultTargetModules else args.mods -- Only submodules of `pkg` will be edited or have info reported on them let pkg := mods[0]!.components.head! -- Load all the modules let mut (_, s) ← (loadModules (mods.map ({module := ·}))).run {} -- Parse the config file let ignoreMods := toBitset s (cfg.ignoreAll?.getD []) let ignoreImps := toBitset s (cfg.ignoreImport?.getD []) let ignore := (cfg.ignore?.getD {}).foldl (init := (∅ : Std.HashMap _ _)) fun m a v => m.insert a (toBitset s v.toList) let noIgnore (i : Nat) := !s.mods[i]!.constNames.isEmpty && -- skip import-only mods ignoreMods &&& (1 <<< i) == 0 && pkg.isPrefixOf s.modNames[i]! -- Run the calculation of the `needs` array in parallel let needs := s.mods.mapIdx fun i mod => if args.downstream || noIgnore i then some <| Task.spawn fun _ => -- remove the module from its own `needs` (calcNeeds s.constToIdx mod ||| (1 <<< i)) ^^^ (1 <<< i) else none if args.downstream then s := { s with needs := needs.map (·.get!.get) } if args.fix then println! "The following changes will be made automatically:" -- Check all selected modules let mut edits : Edits := ∅ for i in [0:s.mods.size], t in needs do if let some t := t then if noIgnore i then let ignoreImps := ignoreImps ||| ignore.getD s.modNames[i]! 0 edits ← visitModule s srcSearchPath ignoreImps i t.get edits args.downstream args.githubStyle args.explain -- Write the config file if args.update then if let some cfgFile := cfgFile then let mut ignore := cfg.ignore?.getD {} let ignoreImport := cfg.ignoreImport?.getD {} let mut ignoreImportSet : NameSet := ignoreImport.foldl .insert {} -- if `args.fix` is true then we assume the errors will be fixed after, -- so it's just reformatting the existing file if !args.fix then if args.global then -- in global mode all the edits are added to `ignoreImport` ignoreImportSet := edits.fold (init := ignoreImportSet) (fun ignore _ (remove, _) => ignore.append remove) else -- in local mode all the edits are added to `ignore` ignore := edits.fold (init := ignore) fun ignore mod (remove, _) => let ns := (ignore.getD mod #[]).foldl (init := remove) (·.insert ·) if ns.isEmpty then ignore.erase mod else ignore.insert mod ns.toArray -- If an entry is in `ignoreAll`, the `ignore` key is redundant for i in cfg.ignoreAll?.getD {} do if ignore.contains i then ignore := ignore.erase i -- If an entry is in `ignoreImport`, the `ignore` value is redundant ignore := ignore.foldl (init := {}) fun ignore mod ns => let ns := ns.filter (!ignoreImportSet.contains ·) if ns.isEmpty then ignore else ignore.insert mod (ns.qsort (·.toString < ·.toString)) -- Sort the lists alphabetically let ignoreImport := (ignoreImportSet.toArray.qsort (·.toString < ·.toString)).toList let cfg : ShakeCfg := { ignoreAll? := cfg.ignoreAll?.filter (!·.isEmpty) ignoreImport? := (some ignoreImport).filter (!·.isEmpty) ignore? := (some ignore).filter (!·.isEmpty) } IO.FS.writeFile cfgFile <| toJson cfg |>.pretty.push '\n' if !args.fix then -- return error if any issues were found return if edits.isEmpty then 0 else 1 -- Apply the edits to existing files let count ← edits.foldM (init := 0) fun count mod (remove, add) => do -- Only edit files in the current package if !pkg.isPrefixOf mod then return count -- Compute the transitive reduction of `add` and convert to a list of names let add := if add == 0 then #[] else Id.run do let mut val := add for i in [0:s.mods.size] do if val &&& (1 <<< i) != 0 then val := val ^^^ (val &&& s.transDeps[i]!) ^^^ (1 <<< i) let mut out := #[] for i in [0:s.mods.size] do if val &&& (1 <<< i) != 0 then out := out.push s.modNames[i]! out.qsort Name.lt -- Parse the input file let (path, inputCtx, imports, insertion) ← try parseHeader srcSearchPath mod catch e => println! e.toString; return count let text := String.Pos.Raw.extract inputCtx.inputString 0 inputCtx.endPos -- Calculate the edit result let mut pos : String.Pos.Raw := 0 let mut out : String := "" let mut seen : NameSet := {} for stx in imports do let mod := importId stx if remove.contains mod || seen.contains mod then out := out ++ String.Pos.Raw.extract text pos stx.raw.getPos?.get! -- We use the end position of the syntax, but include whitespace up to the first newline pos := text.findAux (· == '\n') text.endPos stx.raw.getTailPos?.get! |>.increaseBy 1 seen := seen.insert mod out := out ++ String.Pos.Raw.extract text pos insertion for mod in add do if !seen.contains mod then seen := seen.insert mod out := out ++ s!"import {mod}\n" out := out ++ String.Pos.Raw.extract text insertion text.endPos IO.FS.writeFile path out return count + 1 -- Since we throw an error upon encountering issues, we can be sure that everything worked -- if we reach this point of the script. if count > 0 then println! "Successfully applied {count} suggestions." else println! "No edits required." return 0 -- self-test so that future grammar changes cause a build failure /-- info: #[`Lake.CLI.Main] -/ #guard_msgs (whitespace := lax) in #eval show MetaM _ from do let (_, _, imports, _) ← parseHeaderFromString (← getFileMap).source (← getFileName) return imports.map importId
.lake/packages/batteries/Batteries/Logic.lean
module public import Batteries.Tactic.Alias @[expose] public section instance {f : α → β} [DecidablePred p] : DecidablePred (p ∘ f) := inferInstanceAs <| DecidablePred fun x => p (f x) /-! ## id -/ theorem Function.id_def : @id α = fun x => x := rfl /-! ## decidable -/ protected alias ⟨Decidable.exists_not_of_not_forall, _⟩ := Decidable.not_forall /-! ## classical logic -/ namespace Classical alias ⟨exists_not_of_not_forall, _⟩ := not_forall end Classical /-! ## equality -/ theorem heq_iff_eq {a b : α} : a ≍ b ↔ a = b := ⟨eq_of_heq, heq_of_eq⟩ @[simp] theorem eq_rec_constant {α : Sort _} {a a' : α} {β : Sort _} (y : β) (h : a = a') : (@Eq.rec α a (fun _ _ => β) y a' h) = y := by cases h; rfl theorem congrArg₂ (f : α → β → γ) {x x' : α} {y y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' := by subst hx hy; rfl theorem congrFun₂ {β : α → Sort _} {γ : ∀ a, β a → Sort _} {f g : ∀ a b, γ a b} (h : f = g) (a : α) (b : β a) : f a b = g a b := congrFun (congrFun h _) _ theorem congrFun₃ {β : α → Sort _} {γ : ∀ a, β a → Sort _} {δ : ∀ a b, γ a b → Sort _} {f g : ∀ a b c, δ a b c} (h : f = g) (a : α) (b : β a) (c : γ a b) : f a b c = g a b c := congrFun₂ (congrFun h _) _ _ theorem funext₂ {β : α → Sort _} {γ : ∀ a, β a → Sort _} {f g : ∀ a b, γ a b} (h : ∀ a b, f a b = g a b) : f = g := funext fun _ => funext <| h _ theorem funext₃ {β : α → Sort _} {γ : ∀ a, β a → Sort _} {δ : ∀ a b, γ a b → Sort _} {f g : ∀ a b c, δ a b c} (h : ∀ a b c, f a b c = g a b c) : f = g := funext fun _ => funext₂ <| h _ protected theorem Eq.congr (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) : x₁ = x₂ ↔ y₁ = y₂ := by subst h₁; subst h₂; rfl theorem Eq.congr_left {x y z : α} (h : x = y) : x = z ↔ y = z := by rw [h] theorem Eq.congr_right {x y z : α} (h : x = y) : z = x ↔ z = y := by rw [h] alias congr_arg := congrArg alias congr_arg₂ := congrArg₂ alias congr_fun := congrFun alias congr_fun₂ := congrFun₂ alias congr_fun₃ := congrFun₃ theorem heq_of_cast_eq : ∀ (e : α = β) (_ : cast e a = a'), a ≍ a' | rfl, rfl => .rfl theorem cast_eq_iff_heq : cast e a = a' ↔ a ≍ a' := ⟨heq_of_cast_eq _, fun h => by cases h; rfl⟩ theorem eqRec_eq_cast {α : Sort _} {a : α} {motive : (a' : α) → a = a' → Sort _} (x : motive a rfl) {a' : α} (e : a = a') : @Eq.rec α a motive x a' e = cast (e ▸ rfl) x := by subst e; rfl --Porting note: new theorem. More general version of `eqRec_heq` theorem eqRec_heq_self {α : Sort _} {a : α} {motive : (a' : α) → a = a' → Sort _} (x : motive a rfl) {a' : α} (e : a = a') : @Eq.rec α a motive x a' e ≍ x := by subst e; rfl @[simp] theorem eqRec_heq_iff_heq {α : Sort _} {a : α} {motive : (a' : α) → a = a' → Sort _} {x : motive a rfl} {a' : α} {e : a = a'} {β : Sort _} {y : β} : @Eq.rec α a motive x a' e ≍ y ↔ x ≍ y := by subst e; rfl @[simp] theorem heq_eqRec_iff_heq {α : Sort _} {a : α} {motive : (a' : α) → a = a' → Sort _} {x : motive a rfl} {a' : α} {e : a = a'} {β : Sort _} {y : β} : y ≍ @Eq.rec α a motive x a' e ↔ y ≍ x := by subst e; rfl /-! ## miscellaneous -/ @[simp] theorem not_nonempty_empty : ¬Nonempty Empty := fun ⟨h⟩ => h.elim @[simp] theorem not_nonempty_pempty : ¬Nonempty PEmpty := fun ⟨h⟩ => h.elim -- TODO(Mario): profile first, this is a dangerous instance -- instance (priority := 10) {α} [Subsingleton α] : DecidableEq α -- | a, b => isTrue (Subsingleton.elim a b) -- TODO(Mario): profile adding `@[simp]` to `eq_iff_true_of_subsingleton` /-- If all points are equal to a given point `x`, then `α` is a subsingleton. -/ theorem subsingleton_of_forall_eq (x : α) (h : ∀ y, y = x) : Subsingleton α := ⟨fun a b => h a ▸ h b ▸ rfl⟩ theorem subsingleton_iff_forall_eq (x : α) : Subsingleton α ↔ ∀ y, y = x := ⟨fun _ y => Subsingleton.elim y x, subsingleton_of_forall_eq x⟩ theorem congr_eqRec {β : α → Sort _} (f : (x : α) → β x → γ) (h : x = x') (y : β x) : f x' (Eq.rec y h) = f x y := by cases h; rfl
.lake/packages/batteries/Batteries/Linter.lean
module public meta import Batteries.Linter.UnreachableTactic public meta import Batteries.Linter.UnnecessarySeqFocus
.lake/packages/batteries/Batteries/CodeAction.lean
module public import Batteries.CodeAction.Attr public import Batteries.CodeAction.Basic public import Batteries.CodeAction.Misc public import Batteries.CodeAction.Match
.lake/packages/batteries/Batteries/WF.lean
module import all Init.Prelude import all Init.WF set_option backward.privateInPublic true @[expose] public section /-! # Computable Acc.rec and WellFounded.fix This file exports no public definitions / theorems, but by importing it the compiler will be able to compile `Acc.rec` and functions that use it. For example: Before: ``` -- failed to compile definition, consider marking it as 'noncomputable' -- because it depends on 'WellFounded.fix', and it does not have executable code def log2p1 : Nat → Nat := WellFounded.fix Nat.lt_wfRel.2 fun n IH => let m := n / 2 if h : m < n then IH m h + 1 else 0 ``` After: ``` import Batteries.WF def log2p1 : Nat → Nat := -- works! WellFounded.fix Nat.lt_wfRel.2 fun n IH => let m := n / 2 if h : m < n then IH m h + 1 else 0 #eval log2p1 4 -- 3 ``` -/ namespace Acc instance wfRel {r : α → α → Prop} : WellFoundedRelation { val // Acc r val } where rel := InvImage r (·.1) wf := ⟨fun ac => InvImage.accessible _ ac.2⟩ /-- A computable version of `Acc.rec`. Workaround until Lean has native support for this. -/ @[specialize, elab_as_elim] private def recC {motive : (a : α) → Acc r a → Sort v} (intro : (x : α) → (h : ∀ (y : α), r y x → Acc r y) → ((y : α) → (hr : r y x) → motive y (h y hr)) → motive x (intro x h)) {a : α} (t : Acc r a) : motive a t := intro a (fun _ h => t.inv h) (fun _ hr => recC intro (t.inv hr)) termination_by Subtype.mk a t @[csimp] private theorem rec_eq_recC : @Acc.rec = @Acc.recC := by funext α r motive intro a t induction t with | intro x h ih => rw [recC] dsimp only congr; funext y hr; exact ih _ hr /-- A computable version of `Acc.ndrec`. Workaround until Lean has native support for this. -/ @[inline] abbrev ndrecC {C : α → Sort v} (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) {a : α} (n : Acc r a) : C a := n.recC m @[csimp] theorem ndrec_eq_ndrecC : @Acc.ndrec = @Acc.ndrecC := by funext α r motive intro a t rw [Acc.ndrec, rec_eq_recC, Acc.ndrecC] /-- A computable version of `Acc.ndrecOn`. Workaround until Lean has native support for this. -/ @[inline] abbrev ndrecOnC {C : α → Sort v} {a : α} (n : Acc r a) (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → r y x → C y) → C x) : C a := n.recC m @[csimp] theorem ndrecOn_eq_ndrecOnC : @Acc.ndrecOn = @Acc.ndrecOnC := by funext α r motive intro a t rw [Acc.ndrecOn, rec_eq_recC, Acc.ndrecOnC] end Acc namespace WellFounded /-- Attaches to `x` the proof that `x` is accessible in the given well-founded relation. This can be used in recursive function definitions to explicitly use a different relation than the one inferred by default: ``` def otherWF : WellFounded Nat := … def foo (n : Nat) := … termination_by otherWF.wrap n ``` -/ def wrap {α : Sort u} {r : α → α → Prop} (h : WellFounded r) (x : α) : {x : α // Acc r x} := ⟨_, h.apply x⟩ @[simp] theorem val_wrap {α : Sort u} {r : α → α → Prop} (h : WellFounded r) (x : α) : (h.wrap x).val = x := (rfl) /-- A computable version of `WellFounded.fixF`. Workaround until Lean has native support for this. -/ @[inline] def fixFC {α : Sort u} {r : α → α → Prop} {C : α → Sort v} (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) (a : Acc r x) : C x := by induction a using Acc.recC with | intro x₁ _ ih => exact F x₁ ih @[csimp] theorem fixF_eq_fixFC : @fixF = @fixFC := by funext α r C F x a rw [fixF, Acc.rec_eq_recC, fixFC] /-- A computable version of `fix`. Workaround until Lean has native support for this. -/ @[specialize] def fixC {α : Sort u} {C : α → Sort v} {r : α → α → Prop} (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := F x (fun y _ => fixC hwf F y) termination_by hwf.wrap x unseal fixC @[csimp] theorem fix_eq_fixC : @fix = @fixC := rfl end WellFounded
.lake/packages/batteries/Batteries/Tactic/Instances.lean
module public meta import Lean.Elab.Command public meta import Lean.PrettyPrinter public meta section /-! # `#instances` command The `#instances` command prints lists all instances that apply to the given type, if it is a class. It is similar to `#synth` but it only does the very first step of the instance synthesis algorithm, which is to enumerate potential instances. -/ open Lean Elab Command Meta namespace Batteries.Tactic.Instances /-- `#instances term` prints all the instances for the given class. For example, `#instances Add _` gives all `Add` instances, and `#instances Add Nat` gives the `Nat` instance. The `term` can be any type that can appear in `[...]` binders. Trailing underscores can be omitted, and `#instances Add` and `#instances Add _` are equivalent; the command adds metavariables until the argument is no longer a function. The `#instances` command is closely related to `#synth`, but `#synth` does the full instance synthesis algorithm and `#instances` does the first step of finding potential instances. -/ elab (name := instancesCmd) tk:"#instances " stx:term : command => runTermElabM fun _ => do let type ← Term.elabTerm stx none -- Throw in missing arguments using metavariables. let (args, _, _) ← withDefault <| forallMetaTelescopeReducing (← inferType type) -- Use free variables for explicit quantifiers withDefault <| forallTelescopeReducing (mkAppN type args) fun _ type => do let some className ← isClass? type | throwErrorAt stx "type class instance expected{indentExpr type}" let globalInstances ← getGlobalInstancesIndex let result ← globalInstances.getUnify type let erasedInstances ← getErasedInstances let mut msgs := #[] for e in result.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority do let Expr.const c _ := e.val | unreachable! if erasedInstances.contains c then continue let mut msg := m!"\n" if e.priority != 1000 then -- evalPrio default := 1000 msg := msg ++ m!"(prio {e.priority}) " msgs := msgs.push <| msg ++ MessageData.signature c for linst in ← getLocalInstances do if linst.className == className then msgs := msgs.push m!"(local) {linst.fvar} : {← inferType linst.fvar}" if msgs.isEmpty then logInfoAt tk m!"No instances" else let instances := if msgs.size == 1 then "instance" else "instances" logInfoAt tk <| msgs.reverse.foldl (·++·) m!"{msgs.size} {instances}:\n" @[inherit_doc instancesCmd] macro tk:"#instances" bi:(ppSpace bracketedBinder)* " : " t:term : command => `(command| variable $bi* in #instances%$tk $t)
.lake/packages/batteries/Batteries/Tactic/Lint.lean
module public meta import Batteries.Tactic.Lint.Misc public meta import Batteries.Tactic.Lint.Simp public meta import Batteries.Tactic.Lint.TypeClass public meta import Batteries.Tactic.Lint.Frontend
.lake/packages/batteries/Batteries/Tactic/Alias.lean
module public meta import Lean.Elab.Command public meta import Lean.Elab.DeclarationRange public meta import Lean.Compiler.NoncomputableAttr public meta import Lean.DocString public meta import Batteries.CodeAction.Deprecated public meta section /-! # The `alias` command The `alias` command is used to create synonyms. The plain command can create a synonym of any declaration. There is also a version to create synonyms for the forward and reverse implications of an iff theorem. -/ namespace Batteries.Tactic.Alias open Lean Elab Parser.Command /-- An alias can be in one of three forms -/ inductive AliasInfo where /-- Plain alias -/ | plain (n : Name) /-- Forward direction of an iff alias -/ | forward (n : Name) /-- Reverse direction of an iff alias -/ | reverse (n : Name) deriving Inhabited /-- The name underlying an alias target -/ def AliasInfo.name : AliasInfo → Name | plain n => n | forward n => n | reverse n => n /-- The docstring for an alias. -/ def AliasInfo.toString : AliasInfo → String | plain n => s!"**Alias** of `{n}`." | forward n => s!"**Alias** of the forward direction of `{n}`." | reverse n => s!"**Alias** of the reverse direction of `{n}`." /-- Environment extension for registering aliases -/ initialize aliasExt : SimpleScopedEnvExtension (Name × AliasInfo) (NameMap AliasInfo) ← registerSimpleScopedEnvExtension { addEntry := fun st (n, i) => st.insert n i initial := {} } /-- Get the alias information for a name -/ def getAliasInfo [Monad m] [MonadEnv m] (name : Name) : m (Option AliasInfo) := do return aliasExt.getState (← getEnv) |>.find? name /-- Set the alias info for a new declaration -/ def setAliasInfo [MonadEnv m] (info : AliasInfo) (declName : Name) : m Unit := modifyEnv (aliasExt.addEntry · (declName, info)) /-- Updates the `deprecated` declaration to point to `target` if no target is provided. -/ def setDeprecatedTarget (target : Name) (arr : Array Attribute) : Array Attribute × Bool := StateT.run (m := Id) (s := false) do arr.mapM fun s => do if s.name == `deprecated then if let `(deprecated| deprecated%$tk $[$desc:str]? $[(since := $since)]?) := s.stx then set true let stx := Unhygienic.run `(deprecated| deprecated%$tk $(mkCIdent target) $[$desc:str]? $[(since := $since)]?) pure { s with stx } else pure s else pure s /-- The command `alias name := target` creates a synonym of `target` with the given name. The command `alias ⟨fwd, rev⟩ := target` creates synonyms for the forward and reverse directions of an iff theorem. Use `_` if only one direction is required. These commands accept all modifiers and attributes that `def` and `theorem` do. -/ elab (name := alias) mods:declModifiers "alias " alias:ident " := " name:ident : command => do Lean.withExporting (isExporting := (← Command.getScope).isPublic) do Command.liftTermElabM do let name ← realizeGlobalConstNoOverloadWithInfo name let cinfo ← getConstInfo name let declMods ← elabModifiers mods Lean.withExporting (isExporting := declMods.isInferredPublic (← getEnv)) do let (attrs, machineApplicable) := setDeprecatedTarget name declMods.attrs let declMods := { declMods with computeKind := if isNoncomputable (← getEnv) name then .noncomputable else declMods.computeKind isUnsafe := declMods.isUnsafe || cinfo.isUnsafe attrs } let (declName, _) ← mkDeclName (← getCurrNamespace) declMods alias.getId let decl : Declaration := if wasOriginallyTheorem (← getEnv) name then .thmDecl { cinfo.toConstantVal with name := declName value := mkConst name (cinfo.toConstantVal.levelParams.map mkLevelParam) } else .defnDecl { cinfo.toConstantVal with name := declName value := mkConst name (cinfo.levelParams.map mkLevelParam) hints := .regular 0 -- FIXME safety := if declMods.isUnsafe then .unsafe else .safe } checkNotAlreadyDeclared declName if declMods.isNoncomputable then addDecl decl else addAndCompile decl addDeclarationRangesFromSyntax declName (← getRef) alias Term.addTermInfo' alias (← mkConstWithLevelParams declName) (isBinder := true) if let some (doc, isVerso) := declMods.docString? then addDocStringOf isVerso declName (mkNullNode #[]) doc enableRealizationsForConst declName Term.applyAttributes declName declMods.attrs let info := (← getAliasInfo name).getD <| AliasInfo.plain name setAliasInfo info declName if machineApplicable then modifyEnv (machineApplicableDeprecated.tag · declName) /- alias doesn't trigger the missing docs linter so we add a default. We can't just check `declMods` because a docstring may have been added by an attribute. -/ if (← findDocString? (← getEnv) declName).isNone then let mut doc := info.toString if let some origDoc ← findDocString? (← getEnv) name then doc := s!"{doc}\n\n---\n\n{origDoc}" addDocStringCore declName doc /-- Given a possibly forall-quantified iff expression `prf`, produce a value for one of the implication directions (determined by `mp`). -/ def mkIffMpApp (mp : Bool) (ty prf : Expr) : MetaM Expr := do Meta.forallTelescope ty fun xs ty => do let some (lhs, rhs) := ty.iff? | throwError "Target theorem must have the form `∀ x y z, a ↔ b`" Meta.mkLambdaFVars xs <| mkApp3 (mkConst (if mp then ``Iff.mp else ``Iff.mpr)) lhs rhs (mkAppN prf xs) private def addSide (mp : Bool) (declName : Name) (declMods : Modifiers) (thm : ConstantInfo) : TermElabM Unit := do checkNotAlreadyDeclared declName let value ← mkIffMpApp mp thm.type (mkConst thm.name (thm.levelParams.map mkLevelParam)) let type ← Meta.inferType value addDecl <| Declaration.thmDecl { name := declName value := value type := type levelParams := thm.levelParams } if let some (doc, isVerso) := declMods.docString? then addDocStringOf isVerso declName (mkNullNode #[]) doc Term.applyAttributes declName declMods.attrs let info := match ← getAliasInfo thm.name with | some (.plain name) => if mp then AliasInfo.forward name else AliasInfo.reverse name | _ => if mp then AliasInfo.forward thm.name else AliasInfo.reverse thm.name setAliasInfo info declName /- alias doesn't trigger the missing docs linter so we add a default. We can't just check `declMods` because a docstring may have been added by an attribute. -/ if (← findDocString? (← getEnv) declName).isNone then let mut doc := info.toString if let some origDoc ← findDocString? (← getEnv) thm.name then doc := s!"{doc}\n\n---\n\n{origDoc}" addDocStringCore declName doc @[inherit_doc «alias»] elab (name := aliasLR) mods:declModifiers "alias " "⟨" aliasFwd:binderIdent ", " aliasRev:binderIdent "⟩" " := " name:ident : command => do Lean.withExporting (isExporting := (← Command.getScope).isPublic) do Command.liftTermElabM do let name ← realizeGlobalConstNoOverloadWithInfo name let declMods ← elabModifiers mods let declMods := { declMods with attrs := (setDeprecatedTarget name declMods.attrs).1 } Lean.withExporting (isExporting := declMods.isInferredPublic (← getEnv)) do let thm ← getConstInfo name if let `(binderIdent| $idFwd:ident) := aliasFwd then let (declName, _) ← mkDeclName (← getCurrNamespace) declMods idFwd.getId addSide true declName declMods thm addDeclarationRangesFromSyntax declName (← getRef) idFwd Term.addTermInfo' idFwd (← mkConstWithLevelParams declName) (isBinder := true) if let `(binderIdent| $idRev:ident) := aliasRev then let (declName, _) ← mkDeclName (← getCurrNamespace) declMods idRev.getId addSide false declName declMods thm addDeclarationRangesFromSyntax declName (← getRef) idRev Term.addTermInfo' idRev (← mkConstWithLevelParams declName) (isBinder := true)
.lake/packages/batteries/Batteries/Tactic/Init.lean
module public meta import Lean.Elab.Tactic.ElabTerm public meta section /-! # Simple tactics that are used throughout Batteries. -/ namespace Batteries.Tactic open Lean Parser.Tactic Elab Elab.Tactic Meta /-- `_` in tactic position acts like the `done` tactic: it fails and gives the list of goals if there are any. It is useful as a placeholder after starting a tactic block such as `by _` to make it syntactically correct and show the current goal. -/ macro "_" : tactic => `(tactic| {}) /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ elab (name := exacts) "exacts " "[" hs:term,* "]" : tactic => do for stx in hs.getElems do evalTactic (← `(tactic| exact $stx)) evalTactic (← `(tactic| done)) /-- `by_contra h` proves `⊢ p` by contradiction, introducing a hypothesis `h : ¬p` and proving `False`. * If `p` is a negation `¬q`, `h : q` will be introduced instead of `¬¬q`. * If `p` is decidable, it uses `Decidable.byContradiction` instead of `Classical.byContradiction`. * If `h` is omitted, the introduced variable `_: ¬p` will be anonymous. -/ macro (name := byContra) tk:"by_contra" e?:(ppSpace colGt binderIdent)? : tactic => do let e := match e? with | some e => match e with | `(binderIdent| $e:ident) => e | e => Unhygienic.run `(_%$e) -- HACK: hover fails without Unhygienic here | none => Unhygienic.run `(_%$tk) `(tactic| first | guard_target = Not _; intro $e:term | refine @Decidable.byContradiction _ _ fun $e => ?_ | refine @Classical.byContradiction _ fun $e => ?_) /-- Given a proof `h` of `p`, `absurd h` changes the goal to `⊢ ¬ p`. If `p` is a negation `¬q` then the goal is changed to `⊢ q` instead. -/ macro "absurd " h:term : tactic => -- we can't use `( :)` here as that would make `·` behave weirdly. `(tactic| first | refine @absurd _ _ ?_ $h | refine @absurd _ _ $h ?_) /-- `split_ands` applies `And.intro` until it does not make progress. -/ syntax "split_ands" : tactic macro_rules | `(tactic| split_ands) => `(tactic| repeat' refine And.intro ?_ ?_) /-- `fapply e` is like `apply e` but it adds goals in the order they appear, rather than putting the dependent goals first. -/ elab "fapply " e:term : tactic => evalApplyLikeTactic (·.apply (cfg := {newGoals := .all})) e /-- `eapply e` is like `apply e` but it does not add subgoals for variables that appear in the types of other goals. Note that this can lead to a failure where there are no goals remaining but there are still metavariables in the term: ``` example (h : ∀ x : Nat, x = x → True) : True := by eapply h rfl -- no goals -- (kernel) declaration has metavariables '_example' ``` -/ elab "eapply " e:term : tactic => evalApplyLikeTactic (·.apply (cfg := {newGoals := .nonDependentOnly})) e /-- Deprecated variant of `trivial`. -/ elab (name := triv) "triv" : tactic => throwError "`triv` has been removed; use `trivial` instead" /-- `conv` tactic to close a goal using an equality theorem. -/ macro (name := Conv.exact) "exact " t:term : conv => `(conv| tactic => exact $t) /-- The `conv` tactic `equals` claims that the currently focused subexpression is equal to the given expression, and proves this claim using the given tactic. ``` example (P : (Nat → Nat) → Prop) : P (fun n => n - n) := by conv in (_ - _) => equals 0 => -- current goal: ⊢ n - n = 0 apply Nat.sub_self -- current goal: P (fun n => 0) ``` -/ macro (name := Conv.equals) "equals " t:term " => " tac:tacticSeq : conv => `(conv| tactic => show (_ = $t); next => $tac)
.lake/packages/batteries/Batteries/Tactic/SqueezeScope.lean
module public meta import Lean.Elab.Tactic.SimpTrace public meta section /-! # `squeeze_scope` tactic The `squeeze_scope` tactic allows aggregating multiple calls to `simp` coming from the same syntax but in different branches of execution, such as in `cases x <;> simp`. The reported `simp` call covers all simp lemmas used by this syntax. -/ namespace Batteries.Tactic open Lean Elab Parser Tactic Meta.Tactic /-- `squeeze_scope a => tacs` is part of the implementation of `squeeze_scope`. Inside `tacs`, invocations of `simp` wrapped with `squeeze_wrap a _ => ...` will contribute to the accounting associated to scope `a`. -/ local syntax (name := squeezeScopeIn) "squeeze_scope " ident " => " tacticSeq : tactic /-- `squeeze_wrap a x => tac` is part of the implementation of `squeeze_scope`. Here `tac` will be a `simp` or `dsimp` syntax, and `squeeze_wrap` will run the tactic and contribute the generated `usedSimps` to the `squeezeScopes[a][x]` variable. -/ local syntax (name := squeezeWrap) "squeeze_wrap " ident ppSpace ident " => " tactic : tactic open TSyntax.Compat in /-- The `squeeze_scope` tactic allows aggregating multiple calls to `simp` coming from the same syntax but in different branches of execution, such as in `cases x <;> simp`. The reported `simp` call covers all simp lemmas used by this syntax. ``` @[simp] def bar (z : Nat) := 1 + z @[simp] def baz (z : Nat) := 1 + z @[simp] def foo : Nat → Nat → Nat | 0, z => bar z | _+1, z => baz z example : foo x y = 1 + y := by cases x <;> simp? -- two printouts: -- "Try this: simp only [foo, bar]" -- "Try this: simp only [foo, baz]" example : foo x y = 1 + y := by squeeze_scope cases x <;> simp -- only one printout: "Try this: simp only [foo, baz, bar]" ``` -/ macro (name := squeezeScope) "squeeze_scope " seq:tacticSeq : tactic => do let a ← withFreshMacroScope `(a) let seq ← seq.raw.rewriteBottomUpM fun stx => match stx.getKind with | ``dsimp | ``simpAll | ``simp => do withFreshMacroScope `(tactic| squeeze_wrap $a x => $stx) | _ => pure stx `(tactic| squeeze_scope $a => $seq) open Meta /-- We implement `squeeze_scope` using a global variable that tracks all `squeeze_scope` invocations in flight. It is a map `a => (x => (stx, simps))` where `a` is a unique identifier for the `squeeze_scope` invocation which is shared with all contained simps, and `x` is a unique identifier for a particular piece of simp syntax (which can be called multiple times). Within that, `stx` is the simp syntax itself, and `simps` is the aggregated list of simps used so far. -/ initialize squeezeScopes : IO.Ref (NameMap (NameMap (Syntax × List Simp.UsedSimps))) ← IO.mkRef {} elab_rules : tactic | `(tactic| squeeze_scope $a => $tac) => do let a := a.getId let old ← squeezeScopes.modifyGet fun map => (map.find? a, map.insert a {}) let reset map := match old with | some old => map.insert a old | none => map.erase a let new ← try Elab.Tactic.evalTactic tac squeezeScopes.modifyGet fun map => (map.find? a, reset map) catch e => squeezeScopes.modify reset throw e if let some new := new then for (_, stx, usedSimps) in new do let usedSimps := usedSimps.reverse.foldl (fun s usedSimps => usedSimps.toArray.foldl .insert s) {} let stx' ← mkSimpCallStx stx usedSimps TryThis.addSuggestion stx[0] stx' (origSpan? := stx) elab_rules : tactic | `(tactic| squeeze_wrap $a $x => $tac) => do let stx := tac.raw let stats ← match stx.getKind with | ``Parser.Tactic.simp => do let { ctx, simprocs, dischargeWrapper, .. } ← withMainContext <| mkSimpContext stx (eraseLocal := false) dischargeWrapper.with fun discharge? => simpLocation ctx simprocs discharge? (expandOptLocation stx[5]) | ``Parser.Tactic.simpAll => do let { ctx, simprocs, .. } ← mkSimpContext stx (eraseLocal := true) (kind := .simpAll) (ignoreStarArg := true) let (result?, stats) ← simpAll (← getMainGoal) ctx simprocs match result? with | none => replaceMainGoal [] | some mvarId => replaceMainGoal [mvarId] pure stats | ``Parser.Tactic.dsimp => do let { ctx, simprocs, .. } ← withMainContext <| mkSimpContext stx (eraseLocal := false) (kind := .dsimp) dsimpLocation' ctx simprocs (expandOptLocation stx[5]) | _ => Elab.throwUnsupportedSyntax let a := a.getId; let x := x.getId squeezeScopes.modify fun map => Id.run do let some map1 := map.find? a | return map let newSimps := match map1.find? x with | some (stx, oldSimps) => (stx, stats.usedTheorems :: oldSimps) | none => (stx, [stats.usedTheorems]) map.insert a (map1.insert x newSimps)
.lake/packages/batteries/Batteries/Tactic/PrintOpaques.lean
module public meta import Lean.Elab.Command public meta import Lean.Util.FoldConsts public meta section open Lean Elab Command namespace Batteries.Tactic.CollectOpaques /-- Collects the result of a `CollectOpaques` query. -/ structure State where /-- The set visited constants. -/ visited : NameSet := {} /-- The collected opaque defs. -/ opaques : Array Name := #[] /-- The monad used by `CollectOpaques`. -/ abbrev M := ReaderT Environment <| StateT State MetaM /-- Collect the results for a given constant. -/ partial def collect (c : Name) : M Unit := do let collectExpr (e : Expr) : M Unit := e.getUsedConstants.forM collect let s ← get unless s.visited.contains c do modify fun s => { s with visited := s.visited.insert c } let env ← read match env.find? c with | some (ConstantInfo.ctorInfo _) | some (ConstantInfo.recInfo _) | some (ConstantInfo.inductInfo _) | some (ConstantInfo.quotInfo _) => pure () | some (ConstantInfo.defnInfo v) | some (ConstantInfo.thmInfo v) => unless ← Meta.isProp v.type do collectExpr v.value | some (ConstantInfo.axiomInfo v) | some (ConstantInfo.opaqueInfo v) => unless ← Meta.isProp v.type do modify fun s => { s with opaques := s.opaques.push c } | none => throwUnknownConstant c end CollectOpaques /-- The command `#print opaques X` prints all opaque definitions that `X` depends on. Opaque definitions include partial definitions and axioms. Only dependencies that occur in a computationally relevant context are listed, occurrences within proof terms are omitted. This is useful to determine whether and how a definition is possibly platform dependent, possibly partial, or possibly noncomputable. The command `#print opaques Std.HashMap.insert` shows that `Std.HashMap.insert` depends on the opaque definitions: `System.Platform.getNumBits` and `UInt64.toUSize`. Thus `Std.HashMap.insert` may have different behavior when compiled on a 32 bit or 64 bit platform. The command `#print opaques Stream.forIn` shows that `Stream.forIn` is possibly partial since it depends on the partial definition `Stream.forIn.visit`. Indeed, `Stream.forIn` may not terminate when the input stream is unbounded. The command `#print opaques Classical.choice` shows that `Classical.choice` is itself an opaque definition: it is an axiom. However, `#print opaques Classical.axiomOfChoice` returns nothing since it is a proposition, hence not computationally relevant. (The command `#print axioms` does reveal that `Classical.axiomOfChoice` depends on the `Classical.choice` axiom.) -/ elab "#print" &"opaques" name:ident : command => do let constName ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo name let env ← getEnv let (_, s) ← liftTermElabM <| ((CollectOpaques.collect constName).run env).run {} if s.opaques.isEmpty then logInfo m!"'{constName}' does not use any opaque or partial definitions" else logInfo m!"'{constName}' depends on opaque or partial definitions: {s.opaques.toList}"
.lake/packages/batteries/Batteries/Tactic/PermuteGoals.lean
module public meta import Lean.Elab.Tactic.Basic public meta section /-! # The `on_goal`, `pick_goal`, and `swap` tactics. `pick_goal n` moves the `n`-th goal to the front. If `n` is negative this is counted from the back. `on_goal n => tacSeq` focuses on the `n`-th goal and runs a tactic block `tacSeq`. If `tacSeq` does not close the goal any resulting subgoals are inserted back into the list of goals. If `n` is negative this is counted from the back. `swap` is a shortcut for `pick_goal 2`, which interchanges the 1st and 2nd goals. -/ namespace Batteries.Tactic open Lean Elab.Tactic /-- If the current goals are `g₁ ⋯ gᵢ ⋯ gₙ`, `splitGoalsAndGetNth i` returns `(gᵢ, [g₁, ⋯, gᵢ₋₁], [gᵢ₊₁, ⋯, gₙ])`. If `reverse` is passed as `true`, the `i`-th goal is picked by counting backwards. For instance, `splitGoalsAndGetNth 1 true` puts the last goal in the first component of the returned term. -/ def splitGoalsAndGetNth (nth : Nat) (reverse : Bool := false) : TacticM (MVarId × List MVarId × List MVarId) := do if nth = 0 then throwError "goals are 1-indexed" let goals ← getGoals let nGoals := goals.length if nth > nGoals then throwError "goal index out of bounds" let n := if ¬reverse then nth - 1 else nGoals - nth let (gl, g :: gr) := goals.splitAt n | throwNoGoalsToBeSolved pure (g, gl, gr) /-- `pick_goal n` will move the `n`-th goal to the front. `pick_goal -n` will move the `n`-th goal (counting from the bottom) to the front. See also `Tactic.rotate_goals`, which moves goals from the front to the back and vice-versa. -/ elab "pick_goal " reverse:"-"? n:num : tactic => do let (g, gl, gr) ← splitGoalsAndGetNth n.1.toNat !reverse.isNone setGoals $ g :: (gl ++ gr) /-- `swap` is a shortcut for `pick_goal 2`, which interchanges the 1st and 2nd goals. -/ macro "swap" : tactic => `(tactic| pick_goal 2) /-- `on_goal n => tacSeq` creates a block scope for the `n`-th goal and tries the sequence of tactics `tacSeq` on it. `on_goal -n => tacSeq` does the same, but the `n`-th goal is chosen by counting from the bottom. The goal is not required to be solved and any resulting subgoals are inserted back into the list of goals, replacing the chosen goal. -/ elab "on_goal " reverse:"-"? n:num " => " seq:tacticSeq : tactic => do let (g, gl, gr) ← splitGoalsAndGetNth n.1.toNat !reverse.isNone setGoals [g] evalTactic seq setGoals $ gl ++ (← getUnsolvedGoals) ++ gr
.lake/packages/batteries/Batteries/Tactic/Basic.lean
module public meta import Lean.Elab.Tactic.ElabTerm public meta import Batteries.Linter public meta import Batteries.Tactic.Init public meta import Batteries.Tactic.SeqFocus public meta import Batteries.Util.ProofWanted -- This is an import only file for common tactics used throughout Batteries
.lake/packages/batteries/Batteries/Tactic/Congr.lean
module public meta import Lean.Meta.Tactic.Congr public meta import Lean.Elab.Tactic.Config public meta import Lean.Elab.Tactic.Ext public meta import Lean.Elab.Tactic.RCases public meta section /-! # `congr with` tactic, `rcongr` tactic -/ namespace Batteries.Tactic open Lean Meta Elab Tactic /-- Configuration options for `congr` & `rcongr` -/ structure Congr.Config where /-- If `closePre := true`, it will attempt to close new goals using `Eq.refl`, `HEq.refl`, and `assumption` with reducible transparency. -/ closePre : Bool := true /-- If `closePost := true`, it will try again on goals on which `congr` failed to make progress with default transparency. -/ closePost : Bool := true /-- Function elaborating `Congr.Config` -/ declare_config_elab Congr.elabConfig Congr.Config @[inherit_doc Lean.Parser.Tactic.congr] syntax (name := congrConfig) "congr" Parser.Tactic.config (ppSpace num)? : tactic /-- Apply congruence (recursively) to goals of the form `⊢ f as = f bs` and `⊢ f as ≍ f bs`. * `congr n` controls the depth of the recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr 2` produces the intended `⊢ x + y = y + x`. * If, at any point, a subgoal matches a hypothesis then the subgoal will be closed. * You can use `congr with p (: n)?` to call `ext p (: n)?` to all subgoals generated by `congr`. For example, if the goal is `⊢ f '' s = g '' s` then `congr with x` generates the goal `x : α ⊢ f x = g x`. -/ syntax (name := congrConfigWith) "congr" (Parser.Tactic.config)? (ppSpace colGt num)? " with" (ppSpace colGt rintroPat)* (" : " num)? : tactic elab_rules : tactic | `(tactic| congr $cfg:config $[$n?]?) => do let config ← Congr.elabConfig (mkOptionalNode cfg) let hugeDepth := 1000000 let depth := n?.map (·.getNat) |>.getD hugeDepth liftMetaTactic fun mvarId => mvarId.congrN depth (closePre := config.closePre) (closePost := config.closePost) macro_rules | `(tactic| congr $(cfg)? $(depth)? with $ps* $[: $n]?) => match cfg with | none => `(tactic| congr $(depth)? <;> ext $ps* $[: $n]?) | some cfg => `(tactic| congr $cfg $(depth)? <;> ext $ps* $[: $n]?) /-- Recursive core of `rcongr`. Calls `ext pats <;> congr` and then itself recursively, unless `ext pats <;> congr` made no progress. -/ partial def rcongrCore (g : MVarId) (config : Congr.Config) (pats : List (TSyntax `rcasesPat)) (acc : Array MVarId) : TermElabM (Array MVarId) := do let mut acc := acc for (g, qs) in (← Ext.extCore g pats (failIfUnchanged := false)).2 do let s ← saveState let gs ← g.congrN 1000000 (closePre := config.closePre) (closePost := config.closePost) if ← not <$> g.isAssigned <||> gs.anyM fun g' => return (← g'.getType).eqv (← g.getType) then s.restore acc := acc.push g else for g in gs do acc ← rcongrCore g config qs acc pure acc /-- Repeatedly apply `congr` and `ext`, using the given patterns as arguments for `ext`. There are two ways this tactic stops: * `congr` fails (makes no progress), after having already applied `ext`. * `congr` canceled out the last usage of `ext`. In this case, the state is reverted to before the `congr` was applied. For example, when the goal is ``` ⊢ (fun x => f x + 3) '' s = (fun x => g x + 3) '' s ``` then `rcongr x` produces the goal ``` x : α ⊢ f x = g x ``` This gives the same result as `congr; ext x; congr`. In contrast, `congr` would produce ``` ⊢ (fun x => f x + 3) = (fun x => g x + 3) ``` and `congr with x` (or `congr; ext x`) would produce ``` x : α ⊢ f x + 3 = g x + 3 ``` -/ elab (name := rcongr) "rcongr" cfg:((Parser.Tactic.config)?) ps:(ppSpace colGt rintroPat)* : tactic => do let gs ← rcongrCore (← getMainGoal) (← Congr.elabConfig cfg) (RCases.expandRIntroPats ps).toList #[] replaceMainGoal gs.toList
.lake/packages/batteries/Batteries/Tactic/Case.lean
module public meta import Lean.Elab.Tactic.BuiltinTactic public meta import Lean.Elab.Tactic.RenameInaccessibles public meta section /-! # Extensions to the `case` tactic Adds a variant of `case` that looks for a goal with a particular type, rather than a goal with a particular tag. For consistency with `case`, it takes a tag as well, but the tag can be a hole `_`. Also adds `case'` extensions. -/ namespace Batteries.Tactic open Lean Meta Elab Tactic /-- Clause for a `case ... : ...` tactic. -/ syntax casePattArg := Parser.Tactic.caseArg (" : " term)? /-- The body of a `case ... | ...` tactic that's a tactic sequence (or hole). -/ syntax casePattTac := " => " (hole <|> syntheticHole <|> tacticSeq) /-- The body of a `case ... | ...` tactic that's an exact term. -/ syntax casePattExpr := " := " colGt term /-- The body of a `case ... : ...` tactic. -/ syntax casePattBody := casePattTac <|> casePattExpr /-- * `case _ : t => tac` finds the first goal that unifies with `t` and then solves it using `tac` or else fails. Like `show`, it changes the type of the goal to `t`. The `_` can optionally be a case tag, in which case it only looks at goals whose tag would be considered by `case` (goals with an exact tag match, followed by goals with the tag as a suffix, followed by goals with the tag as a prefix). * `case _ n₁ ... nₘ : t => tac` additionally names the `m` most recent hypotheses with inaccessible names to the given names. The names are renamed before matching against `t`. The `_` can optionally be a case tag. * `case _ : t := e` is short for `case _ : t => exact e`. * `case _ : t₁ | _ : t₂ | ... => tac` is equivalent to `(case _ : t₁ => tac); (case _ : t₂ => tac); ...` but with all matching done on the original list of goals -- each goal is consumed as they are matched, so patterns may repeat or overlap. * `case _ : t` will make the matched goal be the first goal. `case _ : t₁ | _ : t₂ | ...` makes the matched goals be the first goals in the given order. * `case _ : t := _` and `case _ : t := ?m` are the same as `case _ : t` but in the `?m` case the goal tag is changed to `m`. In particular, the goal becomes metavariable `?m`. -/ -- Low priority so that type-free `case` doesn't conflict with core `case`, -- though it should be a drop-in replacement. syntax (name := casePatt) (priority := low) "case " sepBy1(casePattArg, " | ") (casePattBody)? : tactic macro_rules | `(tactic| case $[$ps:casePattArg]|* := $t) => `(tactic| case $[$ps:casePattArg]|* => exact $t) | `(tactic| case $[$ps:casePattArg]|*) => `(tactic| case $[$ps:casePattArg]|* => ?_) /-- `case' _ : t => tac` is similar to the `case _ : t => tac` tactic, but it does not ensure the goal has been solved after applying `tac`, nor does it admit the goal if `tac` failed. Recall that `case` closes the goal using `sorry` when `tac` fails, and the tactic execution is not interrupted. -/ syntax (name := casePatt') (priority := low) "case' " sepBy1(casePattArg, " | ") casePattTac : tactic /-- Filter the `mvarIds` by tag. Returns those `MVarId`s that have `tag` either as its user name, as a suffix of its user name, or as a prefix of its user name. The results are sorted in this order. This is like `Lean.Elab.Tactic.findTag?` but it returns all results rather than just the first. -/ private def filterTag (mvarIds : List MVarId) (tag : Name) : TacticM (List MVarId) := do let gs ← mvarIds.toArray.filterMapM fun mvarId => do let userName := (← mvarId.getDecl).userName if tag == userName then return some (0, mvarId) else if tag.isSuffixOf userName then return some (1, mvarId) else if tag.isPrefixOf userName then return some (2, mvarId) else return none -- Insertion sort is a stable sort: let gs := gs.insertionSort (·.1 < ·.1) return gs |>.map (·.2) |>.toList /-- Find the first goal among those matching `tag` whose type unifies with `patt`. The `renameI` array consists of names to use to rename inaccessibles. The `patt` term is elaborated in the context where the inaccessibles have been renamed. Returns the found goal, goals caused by elaborating `patt`, and the remaining goals. -/ def findGoalOfPatt (gs : List MVarId) (tag : TSyntax ``binderIdent) (patt? : Option Term) (renameI : TSyntaxArray `Lean.binderIdent) : TacticM (MVarId × List MVarId × List MVarId) := Term.withoutErrToSorry do let fgs ← match tag with | `(binderIdent|$tag:ident) => filterTag gs tag.getId | _ => pure gs for g in fgs do let gs := gs.erase g if let some patt := patt? then let s ← saveState try let g ← renameInaccessibles g renameI -- Make a copy of `g` so that we don't assign type hints to `g` if we don't need to. let gCopy ← g.withContext <| mkFreshExprSyntheticOpaqueMVar (← g.getType) (← g.getTag) let g' :: gs' ← run gCopy.mvarId! <| withoutRecover <| evalTactic (← `(tactic| refine_lift show $patt from ?_)) | throwNoGoalsToBeSolved -- This should not happen -- Avoid assigning the type hint if the original type and the new type are -- defeq at reducible transparency. if ← g.withContext <| withReducible <| isDefEq (← g.getType) (← g'.getType) then g.assign (.mvar g') else g.assign gCopy return (g', gs', gs) catch _ => restoreState s else let g ← renameInaccessibles g renameI return (g, [], gs) throwError "\ No goals with tag {tag} unify with the term {patt?.getD (← `(_))}, \ or too many names provided for renaming inaccessible variables." /-- Given a `casePattBody`, either give a synthetic hole or a tactic sequence (along with the syntax for the `=>`). Converts holes into synthetic holes since they are processed with `elabTermWithHoles`. -/ def processCasePattBody (stx : TSyntax ``casePattTac) : TacticM (Term ⊕ (Syntax × TSyntax ``Parser.Tactic.tacticSeq)) := do match stx with | `(casePattTac| => $t:hole) => return Sum.inl ⟨← withRef t `(?_)⟩ | `(casePattTac| => $t:syntheticHole) => return Sum.inl ⟨t⟩ | `(casePattTac| =>%$arr $tac:tacticSeq) => return Sum.inr (arr, tac) | _ => throwUnsupportedSyntax /-- Implementation for `case` and `case'`. -/ def evalCase (close : Bool) (stx : Syntax) (tags : Array (TSyntax `Lean.binderIdent)) (hss : Array (TSyntaxArray `Lean.binderIdent)) (patts? : Array (Option Term)) (caseBody : TSyntax `Batteries.Tactic.casePattTac) : TacticM Unit := do let body ← processCasePattBody caseBody -- Accumulated goals in the hole cases. let mut acc : List MVarId := [] -- Accumulated goals from refining patterns let mut pattref : List MVarId := [] for tag in tags, hs in hss, patt? in patts? do let (g, gs', gs) ← findGoalOfPatt (← getUnsolvedGoals) tag patt? hs setGoals gs pattref := pattref ++ gs' match body with | Sum.inl hole => let gs' ← run g <| withRef hole do let (val, gs') ← elabTermWithHoles hole (← getMainTarget) `case unless ← occursCheck g val do throwError "\ 'case' tactic failed, value{indentExpr val}\n\ depends on the main goal metavariable '{Expr.mvar g}'" g.assign val setGoals gs' acc := acc ++ gs' | Sum.inr (arr, tac) => if close then if tag matches `(binderIdent|$_:ident) then -- If a tag is provided, follow the behavior of the core `case` tactic and clear the tag. g.setTag .anonymous discard <| run g do withCaseRef arr tac do closeUsingOrAdmit (withTacticInfoContext stx (evalTactic tac)) else let mvarTag ← g.getTag let gs' ← run g <| withCaseRef arr tac (evalTactic tac) if let [g'] := gs' then -- If a single goal is remaining, follow the core `case'` tactic and preserve the tag. g'.setTag mvarTag acc := acc ++ gs' setGoals (acc ++ pattref ++ (← getUnsolvedGoals)) elab_rules : tactic | `(tactic| case $[$tags $hss* $[: $patts?]?]|* $caseBody:casePattTac) => do evalCase (close := true) (← getRef) tags hss patts? caseBody elab_rules : tactic | `(tactic| case' $[$tags $hss* $[: $patts?]?]|* $caseBody:casePattTac) => do evalCase (close := false) (← getRef) tags hss patts? caseBody
.lake/packages/batteries/Batteries/Tactic/GeneralizeProofs.lean
module public meta import Lean.Elab.Tactic.Location public meta import Batteries.Lean.Expr /-! # The `generalize_proofs` tactic Generalize any proofs occurring in the goal or in chosen hypotheses, replacing them by local hypotheses. When these hypotheses are named, this makes it easy to refer to these proofs later in a proof, commonly useful when dealing with functions like `Classical.choose` that produce data from proofs. It is also useful to eliminate proof terms to handle issues with dependent types. For example: ```lean def List.nthLe {α} (l : List α) (n : ℕ) (_h : n < l.length) : α := sorry example : List.nthLe [1, 2] 1 (by simp) = 2 := by -- ⊢ [1, 2].nthLe 1 ⋯ = 2 generalize_proofs h -- h : 1 < [1, 2].length -- ⊢ [1, 2].nthLe 1 h = 2 ``` The tactic is similar in spirit to `Lean.Meta.AbstractNestedProofs` in core. One difference is that it the tactic tries to propagate expected types so that we get `1 < [1, 2].length` in the above example rather than `1 < Nat.succ 1`. -/ public meta section namespace Batteries.Tactic open Lean Meta Elab Parser.Tactic Elab.Tactic initialize registerTraceClass `Tactic.generalize_proofs namespace GeneralizeProofs /-- Configuration for the `generalize_proofs` tactic. -/ structure Config where /-- The maximum recursion depth when generalizing proofs. When `maxDepth > 0`, then proofs are generalized from the types of the generalized proofs too. -/ maxDepth : Nat := 8 /-- When `abstract` is `true`, then the tactic will create universally quantified proofs to account for bound variables. When it is `false` then such proofs are left alone. -/ abstract : Bool := true /-- (Debugging) When `true`, enables consistency checks. -/ debug : Bool := false /-- Elaborates a `Parser.Tactic.config` for `generalize_proofs`. -/ declare_config_elab elabConfig Config /-- State for the `MGen` monad. -/ structure GState where /-- Mapping from propositions to an fvar in the local context with that type. -/ propToFVar : ExprMap Expr /-- Monad used to generalize proofs. Carries `Mathlib.Tactic.GeneralizeProofs.Config` and `Mathlib.Tactic.GeneralizeProofs.State`. -/ abbrev MGen := ReaderT Config <| StateRefT GState MetaM /-- Inserts a prop/fvar pair into the `propToFVar` map. -/ def MGen.insertFVar (prop fvar : Expr) : MGen Unit := modify fun s => { s with propToFVar := s.propToFVar.insert prop fvar } /-- Context for the `MAbs` monad. -/ structure AContext where /-- The local fvars corresponding to bound variables. Abstraction needs to be sure that these variables do not appear in abstracted terms. -/ fvars : Array Expr := #[] /-- A copy of `propToFVar` from `GState`. -/ propToFVar : ExprMap Expr /-- The recursion depth, for how many times `visit` is called from within `visitProof. -/ depth : Nat := 0 /-- The initial local context, for resetting when recursing. -/ initLCtx : LocalContext /-- The tactic configuration. -/ config : Config /-- State for the `MAbs` monad. -/ structure AState where /-- The prop/proof triples to add to the local context. The proofs must not refer to fvars in `fvars`. -/ generalizations : Array (Expr × Expr) := #[] /-- Map version of `generalizations`. Use `MAbs.findProof?` and `MAbs.insertProof`. -/ propToProof : ExprMap Expr := {} /-- Monad used to abstract proofs, to prepare for generalization. Has a cache (of expr/type? pairs), and it also has a reader context `Mathlib/Tactic/GeneralizeProofs/AContext.lean` and a state `Mathlib/Tactic/GeneralizeProofs/AState.lean`. -/ abbrev MAbs := ReaderT AContext <| MonadCacheT (Expr × Option Expr) Expr <| StateRefT AState MetaM /-- Runs `MAbs` in `MGen`. Returns the value and the `generalizations`. -/ def MGen.runMAbs {α : Type} (mx : MAbs α) : MGen (α × Array (Expr × Expr)) := do let s ← get let (x, s') ← mx |>.run { initLCtx := ← getLCtx, propToFVar := s.propToFVar, config := (← read) } |>.run |>.run {} return (x, s'.generalizations) /-- Finds a proof of `prop` by looking at `propToFVar` and `propToProof`. -/ def MAbs.findProof? (prop : Expr) : MAbs (Option Expr) := do if let some pf := (← read).propToFVar[prop]? then return pf else return (← get).propToProof[prop]? /-- Generalize `prop`, where `proof` is its proof. -/ def MAbs.insertProof (prop pf : Expr) : MAbs Unit := do if (← read).config.debug then unless ← isDefEq prop (← inferType pf) do throwError "insertProof: proof{indentD pf}does not have type{indentD prop}" unless ← Lean.MetavarContext.isWellFormed (← read).initLCtx pf do throwError "insertProof: proof{indentD pf}\nis not well-formed in the initial context\n\ fvars: {(← read).fvars}" unless ← Lean.MetavarContext.isWellFormed (← read).initLCtx prop do throwError "insertProof: proof{indentD prop}\nis not well-formed in the initial context\n\ fvars: {(← read).fvars}" modify fun s => { s with generalizations := s.generalizations.push (prop, pf) propToProof := s.propToProof.insert prop pf } /-- Runs `x` with an additional local variable. -/ def MAbs.withLocal {α : Type} (fvar : Expr) (x : MAbs α) : MAbs α := withReader (fun r => {r with fvars := r.fvars.push fvar}) x /-- Runs `x` with an increased recursion depth and the initial local context, clearing `fvars`. -/ def MAbs.withRecurse {α : Type} (x : MAbs α) : MAbs α := do withLCtx (← read).initLCtx (← getLocalInstances) do withReader (fun r => {r with fvars := #[], depth := r.depth + 1}) x /-- Computes expected types for each argument to `f`, given that the type of `mkAppN f args` is supposed to be `ty?` (where if `ty?` is none, there's no type to propagate inwards). -/ def appArgExpectedTypes (f : Expr) (args : Array Expr) (ty? : Option Expr) : MetaM (Array (Option Expr)) := withTransparency .all <| withNewMCtxDepth do -- Try using the expected type, but (*) below might find a bad solution (guard ty?.isSome *> go f args ty?) <|> go f args none where /-- Core implementation for `appArgExpectedTypes`. -/ go (f : Expr) (args : Array Expr) (ty? : Option Expr) : MetaM (Array (Option Expr)) := do -- Metavariables for each argument to `f`: let mut margs := #[] -- The current type of `mAppN f margs`: let mut fty ← inferType f -- Whether we have already unified the type `ty?` with `fty` (once `margs` is filled) let mut unifiedFTy := false for h : i in [0 : args.size] do unless i < margs.size do let (margs', _, fty') ← forallMetaBoundedTelescope fty (args.size - i) if margs'.isEmpty then throwError "could not make progress at argument {i}" fty := fty' margs := margs ++ margs' let arg := args[i] let marg := margs[i]! if !unifiedFTy && margs.size == args.size then if let some ty := ty? then unifiedFTy := (← observing? <| isDefEq fty ty).getD false -- (*) unless ← isDefEq (← inferType marg) (← inferType arg) do throwError s!"failed isDefEq types {i}, {← ppExpr marg}, {← ppExpr arg}" unless ← isDefEq marg arg do throwError s!"failed isDefEq values {i}, {← ppExpr marg}, {← ppExpr arg}" unless ← marg.mvarId!.isAssigned do marg.mvarId!.assign arg margs.mapM fun marg => do -- Note: all mvars introduced by `appArgExpectedTypes` are assigned by this point -- so there is no mvar leak. return (← instantiateMVars (← inferType marg)).cleanupAnnotations /-- Does `mkLambdaFVars fvars e` but 1. zeta reduces let bindings 2. only includes used fvars 3. returns the list of fvars that were actually abstracted -/ def mkLambdaFVarsUsedOnly (fvars : Array Expr) (e : Expr) : MetaM (Array Expr × Expr) := do let mut e := e let mut fvars' : List Expr := [] for i' in [0:fvars.size] do let i := fvars.size - i' - 1 let fvar := fvars[i]! e ← mkLambdaFVars #[fvar] e match e with | .letE _ _ v b _ => e := b.instantiate1 v | .lam _ _ b _ => if b.hasLooseBVars then fvars' := fvar :: fvars' else e := b | _ => unreachable! return (fvars'.toArray, e) /-- Abstract proofs occurring in the expression. A proof is *abstracted* if it is of the form `f a b ...` where `a b ...` are bound variables (that is, they are variables that are not present in the initial local context) and where `f` contains no bound variables. In this form, `f` can be immediately lifted to be a local variable and generalized. The abstracted proofs are recorded in the state. This function is careful to track the type of `e` based on where it's used, since the inferred type might be different. For example, `(by simp : 1 < [1, 2].length)` has `1 < Nat.succ 1` as the inferred type, but from knowing it's an argument to `List.nthLe` we can deduce `1 < [1, 2].length`. -/ partial def abstractProofs (e : Expr) (ty? : Option Expr) : MAbs Expr := do if (← read).depth ≤ (← read).config.maxDepth then MAbs.withRecurse <| visit (← instantiateMVars e) ty? else return e where /-- Core implementation of `abstractProofs`. -/ visit (e : Expr) (ty? : Option Expr) : MAbs Expr := do trace[Tactic.generalize_proofs] "visit (fvars := {(← read).fvars}) e is {e}" if (← read).config.debug then if let some ty := ty? then unless ← isDefEq (← inferType e) ty do throwError "visit: type of{indentD e}\nis not{indentD ty}" if e.isAtomic then return e else checkCache (e, ty?) fun _ => do if ← isProof e then visitProof e ty? else match e with | .forallE n t b i => withLocalDecl n i (← visit t none) fun x => MAbs.withLocal x do mkForallFVars #[x] (← visit (b.instantiate1 x) none) | .lam n t b i => do withLocalDecl n i (← visit t none) fun x => MAbs.withLocal x do let ty'? ← if let some ty := ty? then let .forallE _ _ tyB _ ← whnfD ty | throwError "Expecting forall in abstractProofs .lam" pure <| some <| tyB.instantiate1 x else pure none mkLambdaFVars #[x] (← visit (b.instantiate1 x) ty'?) | .letE n t v b nondep => let t' ← visit t none mapLetDecl n t' (← visit v t') (nondep := nondep) fun x => MAbs.withLocal x do visit (b.instantiate1 x) ty? | .app .. => e.withApp fun f args => do let f' ← visit f none let argTys ← appArgExpectedTypes f' args ty? let mut args' := #[] for arg in args, argTy in argTys do args' := args'.push <| ← visit arg argTy return mkAppN f' args' | .mdata _ b => return e.updateMData! (← visit b ty?) -- Giving up propagating expected types for `.proj`, which we shouldn't see anyway: | .proj _ _ b => return e.updateProj! (← visit b none) | _ => unreachable! /-- Core implementation of abstracting a proof. -/ visitProof (e : Expr) (ty? : Option Expr) : MAbs Expr := do let eOrig := e let fvars := (← read).fvars -- Strip metadata and beta reduce, in case there are some false dependencies let e := e.withApp' fun f args => f.beta args -- If head is atomic and arguments are bound variables, then it's already abstracted. if e.withApp' fun f args => f.isAtomic && args.all fvars.contains then return e -- Abstract `fvars` out of `e` to make the abstracted proof `pf` -- The use of `mkLambdaFVarsUsedOnly` is *key* to make sure that the fvars in `fvars` -- don't leak into the expression, since that would poison the cache in `MonadCacheT`. let e ← if let some ty := ty? then if (← read).config.debug then unless ← isDefEq ty (← inferType e) do throwError m!"visitProof: incorrectly propagated type{indentD ty}\nfor{indentD e}" mkExpectedTypeHint e ty else pure e trace[Tactic.generalize_proofs] "before mkLambdaFVarsUsedOnly, e = {e}\nfvars={fvars}" if (← read).config.debug then unless ← Lean.MetavarContext.isWellFormed (← getLCtx) e do throwError m!"visitProof: proof{indentD e}\nis not well-formed in the current context\n\ fvars: {fvars}" let (fvars', pf) ← mkLambdaFVarsUsedOnly fvars e if !(← read).config.abstract && !fvars'.isEmpty then trace[Tactic.generalize_proofs] "'abstract' is false and proof uses fvars, not abstracting" return eOrig trace[Tactic.generalize_proofs] "after mkLambdaFVarsUsedOnly, pf = {pf}\nfvars'={fvars'}" if (← read).config.debug then unless ← Lean.MetavarContext.isWellFormed (← read).initLCtx pf do throwError m!"visitProof: proof{indentD pf}\nis not well-formed in the initial context\n\ fvars: {fvars}\n{(← mkFreshExprMVar none).mvarId!}" let pfTy ← instantiateMVars (← inferType pf) -- Visit the proof type to normalize it and abstract more proofs let pfTy ← abstractProofs pfTy none -- Check if there is already a recorded proof for this proposition. trace[Tactic.generalize_proofs] "finding {pfTy}" if let some pf' ← MAbs.findProof? pfTy then trace[Tactic.generalize_proofs] "found proof" return mkAppN pf' fvars' -- Record the proof in the state and return the proof. MAbs.insertProof pfTy pf trace[Tactic.generalize_proofs] "added proof" return mkAppN pf fvars' /-- Create a mapping of all propositions in the local context to their fvars. -/ def initialPropToFVar : MetaM (ExprMap Expr) := do -- Visit decls in reverse order so that in case there are duplicates, -- earlier proofs are preferred (← getLCtx).foldrM (init := {}) fun decl m => do if !decl.isImplementationDetail then let ty := (← instantiateMVars decl.type).cleanupAnnotations if ← Meta.isProp ty then return m.insert ty decl.toExpr return m /-- Generalizes the proofs in the type `e` and runs `k` in a local context with these propositions. This continuation `k` is passed 1. an array of fvars for the propositions 2. an array of proof terms (extracted from `e`) that prove these propositions 3. the generalized `e`, which refers to these fvars The `propToFVar` map is updated with the new proposition fvars. -/ partial def withGeneralizedProofs {α : Type} [Nonempty α] (e : Expr) (ty? : Option Expr) (k : Array Expr → Array Expr → Expr → MGen α) : MGen α := do let propToFVar := (← get).propToFVar trace[Tactic.generalize_proofs] "pre-abstracted{indentD e}\npropToFVar: {propToFVar.toArray}" let (e, generalizations) ← MGen.runMAbs <| abstractProofs e ty? trace[Tactic.generalize_proofs] "\ post-abstracted{indentD e}\nnew generalizations: {generalizations}" let rec /-- Core loop for `withGeneralizedProofs`, adds generalizations one at a time. -/ go [Nonempty α] (i : Nat) (fvars pfs : Array Expr) (proofToFVar propToFVar : ExprMap Expr) : MGen α := do if h : i < generalizations.size then let (ty, pf) := generalizations[i] let ty := (← instantiateMVars (ty.replace proofToFVar.get?)).cleanupAnnotations withLocalDeclD (← mkFreshUserName `pf) ty fun fvar => do go (i + 1) (fvars := fvars.push fvar) (pfs := pfs.push pf) (proofToFVar := proofToFVar.insert pf fvar) (propToFVar := propToFVar.insert ty fvar) else withNewLocalInstances fvars 0 do let e' := e.replace proofToFVar.get? trace[Tactic.generalize_proofs] "after: e' = {e}" modify fun s => { s with propToFVar } k fvars pfs e' go 0 #[] #[] (proofToFVar := {}) (propToFVar := propToFVar) /-- Main loop for `Lean.MVarId.generalizeProofs`. The `fvars` array is the array of fvars to generalize proofs for, and `rfvars` is the array of fvars that have been reverted. The `g` metavariable has all of these fvars reverted. -/ partial def generalizeProofsCore (g : MVarId) (fvars rfvars : Array FVarId) (target : Bool) : MGen (Array Expr × MVarId) := go g 0 #[] where /-- Loop for `generalizeProofsCore`. -/ go (g : MVarId) (i : Nat) (hs : Array Expr) : MGen (Array Expr × MVarId) := g.withContext do let tag ← g.getTag if h : i < rfvars.size then trace[Tactic.generalize_proofs] "generalizeProofsCore {i}{g}\n{(← get).propToFVar.toArray}" let fvar := rfvars[i] if fvars.contains fvar then -- This is one of the hypotheses that was intentionally reverted. let tgt ← instantiateMVars <| ← g.getType let ty := (if tgt.isLet then tgt.letType! else tgt.bindingDomain!).cleanupAnnotations if ← pure tgt.isLet <&&> Meta.isProp ty then -- Clear the proof value (using proof irrelevance) and `go` again let tgt' := Expr.forallE tgt.letName! ty tgt.letBody! .default let g' ← mkFreshExprSyntheticOpaqueMVar tgt' tag g.assign <| .app g' tgt.letValue! return ← go g'.mvarId! i hs if let some pf := (← get).propToFVar[ty]? then -- Eliminate this local hypothesis using the pre-existing proof, using proof irrelevance let tgt' := tgt.bindingBody!.instantiate1 pf let g' ← mkFreshExprSyntheticOpaqueMVar tgt' tag g.assign <| .lam tgt.bindingName! tgt.bindingDomain! g' tgt.bindingInfo! return ← go g'.mvarId! (i + 1) hs -- Now the main case, handling forall or let match tgt with | .forallE n t b bi => let prop ← Meta.isProp t withGeneralizedProofs t none fun hs' pfs' t' => do let t' := t'.cleanupAnnotations let tgt' := Expr.forallE n t' b bi let g' ← mkFreshExprSyntheticOpaqueMVar tgt' tag g.assign <| mkAppN (← mkLambdaFVars hs' g') pfs' let (fvar', g') ← g'.mvarId!.intro1P g'.withContext do Elab.pushInfoLeaf <| .ofFVarAliasInfo { id := fvar', baseId := fvar, userName := ← fvar'.getUserName } if prop then -- Make this prop available as a proof MGen.insertFVar t' (.fvar fvar') go g' (i + 1) (hs ++ hs') | .letE n t v b nondep => withGeneralizedProofs t none fun hs' pfs' t' => do withGeneralizedProofs v t' fun hs'' pfs'' v' => do let tgt' := Expr.letE n t' v' b nondep let g' ← mkFreshExprSyntheticOpaqueMVar tgt' tag g.assign <| mkAppN (← mkLambdaFVars (hs' ++ hs'') g') (pfs' ++ pfs'') let (fvar', g') ← g'.mvarId!.intro1P g'.withContext do Elab.pushInfoLeaf <| .ofFVarAliasInfo { id := fvar', baseId := fvar, userName := ← fvar'.getUserName } go g' (i + 1) (hs ++ hs' ++ hs'') | _ => unreachable! else -- This is one of the hypotheses that was incidentally reverted. let (fvar', g') ← g.intro1P g'.withContext do Elab.pushInfoLeaf <| .ofFVarAliasInfo { id := fvar', baseId := fvar, userName := ← fvar'.getUserName } go g' (i + 1) hs else if target then trace[Tactic.generalize_proofs] "\ generalizeProofsCore target{g}\n{(← get).propToFVar.toArray}" withGeneralizedProofs (← g.getType) none fun hs' pfs' ty' => do let g' ← mkFreshExprSyntheticOpaqueMVar ty' tag g.assign <| mkAppN (← mkLambdaFVars hs' g') pfs' return (hs ++ hs', g'.mvarId!) else return (hs, g) end GeneralizeProofs /-- Generalize proofs in the hypotheses `fvars` and, if `target` is true, the target. Returns the fvars for the generalized proofs and the new goal. If a hypothesis is a proposition and a `let` binding, this will clear the value of the let binding. If a hypothesis is a proposition that already appears in the local context, it will be eliminated. Only *nontrivial* proofs are generalized. These are proofs that aren't of the form `f a b ...` where `f` is atomic and `a b ...` are bound variables. These sorts of proofs cannot be meaningfully generalized, and also these are the sorts of proofs that are left in a term after generalization. -/ partial def _root_.Lean.MVarId.generalizeProofs (g : MVarId) (fvars : Array FVarId) (target : Bool) (config : GeneralizeProofs.Config := {}) : MetaM (Array Expr × MVarId) := do let (rfvars, g) ← g.revert fvars (clearAuxDeclsInsteadOfRevert := true) g.withContext do let s := { propToFVar := ← GeneralizeProofs.initialPropToFVar } GeneralizeProofs.generalizeProofsCore g fvars rfvars target |>.run config |>.run' s /-- `generalize_proofs ids* [at locs]?` generalizes proofs in the current goal, turning them into new local hypotheses. - `generalize_proofs` generalizes proofs in the target. - `generalize_proofs at h₁ h₂` generalized proofs in hypotheses `h₁` and `h₂`. - `generalize_proofs at *` generalizes proofs in the entire local context. - `generalize_proofs pf₁ pf₂ pf₃` uses names `pf₁`, `pf₂`, and `pf₃` for the generalized proofs. These can be `_` to not name proofs. If a proof is already present in the local context, it will use that rather than create a new local hypothesis. When doing `generalize_proofs at h`, if `h` is a let binding, its value is cleared, and furthermore if `h` duplicates a preceding local hypothesis then it is eliminated. The tactic is able to abstract proofs from under binders, creating universally quantified proofs in the local context. To disable this, use `generalize_proofs -abstract`. The tactic is also set to recursively abstract proofs from the types of the generalized proofs. This can be controlled with the `maxDepth` configuration option, with `generalize_proofs (config := { maxDepth := 0 })` turning this feature off. For example: ```lean def List.nthLe {α} (l : List α) (n : ℕ) (_h : n < l.length) : α := sorry example : List.nthLe [1, 2] 1 (by simp) = 2 := by -- ⊢ [1, 2].nthLe 1 ⋯ = 2 generalize_proofs h -- h : 1 < [1, 2].length -- ⊢ [1, 2].nthLe 1 h = 2 ``` -/ elab (name := generalizeProofsElab) "generalize_proofs" config:Parser.Tactic.optConfig hs:(ppSpace colGt binderIdent)* loc?:(location)? : tactic => withMainContext do let config ← GeneralizeProofs.elabConfig config let (fvars, target) ← match expandOptLocation (Lean.mkOptionalNode loc?) with | .wildcard => pure ((← getLCtx).getFVarIds, true) | .targets t target => pure (← getFVarIds t, target) liftMetaTactic1 fun g => do let (pfs, g) ← g.generalizeProofs fvars target config -- Rename the proofs using `hs` and record info g.withContext do let mut lctx ← getLCtx for h in hs, fvar in pfs do if let `(binderIdent| $s:ident) := h then lctx := lctx.setUserName fvar.fvarId! s.getId Expr.addLocalVarInfoForBinderIdent fvar h withLCtx lctx (← getLocalInstances) do let g' ← mkFreshExprSyntheticOpaqueMVar (← g.getType) (← g.getTag) g.assign g' return g'.mvarId! end Batteries.Tactic
.lake/packages/batteries/Batteries/Tactic/Unreachable.lean
module public meta import Lean.Elab.Tactic.Basic public meta section namespace Batteries.Tactic /-- This tactic causes a panic when run (at compile time). (This is distinct from `exact unreachable!`, which inserts code which will panic at run time.) It is intended for tests to assert that a tactic will never be executed, which is otherwise an unusual thing to do (and the `unreachableTactic` linter will give a warning if you do). The `unreachableTactic` linter has a special exception for uses of `unreachable!`. ``` example : True := by trivial <;> unreachable! ``` -/ elab (name := unreachable) "unreachable!" : tactic => do panic! "unreachable tactic has been reached" -- Note that `panic!` does not actually halt execution or early exit, -- so we still have to throw an error after panicking. throwError "unreachable tactic has been reached" @[inherit_doc unreachable] macro (name := unreachableConv) "unreachable!" : conv => `(conv| tactic' => unreachable!)
.lake/packages/batteries/Batteries/Tactic/SeqFocus.lean
module public meta import Lean.Elab.Tactic.Basic public meta section open Lean Elab Meta Tactic namespace Batteries.Tactic /-- Assuming there are `n` goals, `map_tacs [t1; t2; ...; tn]` applies each `ti` to the respective goal and leaves the resulting subgoals. -/ elab "map_tacs " "[" ts:sepBy(tactic, "; ") "]" : tactic => do let goals ← getUnsolvedGoals let tacs := ts.getElems let length := tacs.size if length < goals.length then throwError "not enough tactics" else if length > goals.length then throwError "too many tactics" let mut goalsNew := #[] for tac in tacs, goal in goals do if ← goal.isAssigned then continue setGoals [goal] try evalTactic tac goalsNew := goalsNew ++ (← getUnsolvedGoals) catch ex => if (← read).recover then logException ex goalsNew := goalsNew.push goal else throw ex setGoals goalsNew.toList /-- `t <;> [t1; t2; ...; tn]` focuses on the first goal and applies `t`, which should result in `n` subgoals. It then applies each `ti` to the corresponding goal and collects the resulting subgoals. -/ macro:1 (name := seq_focus) t:tactic " <;> " "[" ts:sepBy(tactic, "; ") "]" : tactic => `(tactic| focus ( $t:tactic; map_tacs [$ts;*]) )
.lake/packages/batteries/Batteries/Tactic/Exact.lean
module public meta import Batteries.Tactic.Alias public meta section /-! # `exact` tactic (`MetaM` version) -/ open Lean Meta /-- `MetaM` version of `Lean.Elab.Tactic.evalExact`: add `mvarId := x` to the metavariable assignment. This method wraps `Lean.MVarId.assign`, checking whether `mvarId` is already assigned, and whether the expression has the right type. -/ def Lean.MVarId.assignIfDefEq (g : MVarId) (e : Expr) : MetaM Unit := do guard <| ← isDefEq (← g.getType) (← inferType e) g.checkNotAssigned `assignIfDefEq g.assign e @[deprecated (since := "2025-04-09")] alias Lean.MVarId.assignIfDefeq := Lean.MVarId.assignIfDefEq
.lake/packages/batteries/Batteries/Tactic/NoMatch.lean
module public meta import Lean.DocString public meta import Lean.Elab.Tactic.Basic public meta section /-! Deprecation warnings for `match ⋯ with.`, `fun.`, `λ.`, and `intro.`. -/ namespace Batteries.Tactic open Lean Elab Term Tactic Parser.Term /-- The syntax `match ⋯ with.` has been deprecated in favor of `nomatch ⋯`. Both now support multiple discriminants. -/ elab (name := matchWithDot) tk:"match " t:term,* " with" "." : term <= expectedType? => do logWarningAt tk (← findDocString? (← getEnv) ``matchWithDot).get! elabTerm (← `(nomatch%$tk $[$t],*)) expectedType? /-- The syntax `fun.` has been deprecated in favor of `nofun`. -/ elab (name := funDot) tk:"fun" "." : term <= expectedType? => do logWarningAt tk (← findDocString? (← getEnv) ``funDot).get! elabTerm (← `(nofun)) expectedType? /-- The syntax `λ.` has been deprecated in favor of `nofun`. -/ elab (name := lambdaDot) tk:"fun" "." : term <= expectedType? => do logWarningAt tk (← findDocString? (← getEnv) ``lambdaDot).get! elabTerm (← `(nofun)) expectedType? @[inherit_doc matchWithDot] macro "match " discrs:term,* " with" "." : tactic => `(tactic| exact match $discrs,* with.) /-- The syntax `intro.` is deprecated in favor of `nofun`. -/ elab (name := introDot) tk:"intro" "." : tactic => do logWarningAt tk (← findDocString? (← getEnv) ``introDot).get! evalTactic (← `(tactic| nofun))
.lake/packages/batteries/Batteries/Tactic/PrintDependents.lean
module public meta import Lean.Elab.Command public meta import Lean.Util.FoldConsts public meta section /-! # `#print dependents` command This is a variation on `#print axioms` where one instead specifies the axioms to avoid, and it prints a list of all the theorems in the file that depend on that axiom, and the list of all theorems directly referenced that are "to blame" for this dependency. Useful for debugging unexpected dependencies. -/ namespace Batteries.Tactic open Lean Elab Command namespace CollectDependents /-- Collects the result of a `CollectDependents` query. -/ structure State where /-- If true, an axiom not in the initial list will be considered as marked. -/ otherAxiom : Bool := true /-- The cached results on visited constants. -/ result : NameMap Bool := {} /-- The monad used by `CollectDependents`. -/ abbrev M := ReaderT Environment $ StateM State /-- Constructs the initial state, marking the constants in `cs`. The result of `collect` will say whether a given declaration depends transitively on one of these constants. If `otherAxiom` is true, any axiom not specified in `cs` will also be tracked. -/ def mkState (cs : Array (Name × Bool)) (otherAxiom := true) : State := { otherAxiom, result := cs.foldl (fun r (c, b) => r.insert c b) {} } /-- Collect the results for a given constant. -/ partial def collect (c : Name) : M Bool := do let collectExpr (e : Expr) : M Bool := e.getUsedConstants.anyM collect let s ← get if let some b := s.result.find? c then return b modify fun s => { s with result := s.result.insert c false } let env ← read let r ← match env.find? c with | some (ConstantInfo.axiomInfo _) => pure s.otherAxiom | some (ConstantInfo.defnInfo v) => collectExpr v.type <||> collectExpr v.value | some (ConstantInfo.thmInfo v) => collectExpr v.type <||> collectExpr v.value | some (ConstantInfo.opaqueInfo v) => collectExpr v.type <||> collectExpr v.value | some (ConstantInfo.quotInfo _) => pure false | some (ConstantInfo.ctorInfo v) => collectExpr v.type | some (ConstantInfo.recInfo v) => collectExpr v.type | some (ConstantInfo.inductInfo v) => collectExpr v.type <||> v.ctors.anyM collect | none => pure false modify fun s => { s with result := s.result.insert c r } pure r end CollectDependents /-- The command `#print dependents X Y` prints a list of all the declarations in the file that transitively depend on `X` or `Y`. After each declaration, it shows the list of all declarations referred to directly in the body which also depend on `X` or `Y`. For example, `#print axioms bar'` below shows that `bar'` depends on `Classical.choice`, but not why. `#print dependents Classical.choice` says that `bar'` depends on `Classical.choice` because it uses `foo` and `foo` uses `Classical.em`. `bar` is not listed because it is proved without using `Classical.choice`. ``` import Batteries.Tactic.PrintDependents theorem foo : x = y ∨ x ≠ y := Classical.em _ theorem bar : 1 = 1 ∨ 1 ≠ 1 := by simp theorem bar' : 1 = 1 ∨ 1 ≠ 1 := foo #print axioms bar' -- 'bar'' depends on axioms: [Classical.choice, Quot.sound, propext] #print dependents Classical.choice -- foo: Classical.em -- bar': foo ``` -/ elab tk:"#print" &"dependents" ids:(ppSpace colGt ident)* : command => do let env ← getEnv let ids ← ids.mapM fun c => return (← liftCoreM <| realizeGlobalConstNoOverloadWithInfo c, true) let init := CollectDependents.mkState ids false let mut state := init let mut out := #[] for (c, _) in env.constants.map₂ do let (b, state') := CollectDependents.collect c |>.run env |>.run state state := state' if b then if let some ranges ← findDeclarationRanges? c then out := out.push (c, ranges.range.pos.1) let msg ← out.qsort (·.2 < ·.2) |>.mapM fun (c, _) => do let mut msg := m!"{MessageData.ofConst (← mkConstWithLevelParams c)}: " if init.result.contains c then msg := msg ++ m!"<specified>" else let consts := match env.find? c with | some (ConstantInfo.defnInfo v) => v.type.getUsedConstants ++ v.value.getUsedConstants | some (ConstantInfo.thmInfo v) => v.type.getUsedConstants ++ v.value.getUsedConstants | some (ConstantInfo.opaqueInfo v) => v.type.getUsedConstants ++ v.value.getUsedConstants | some (ConstantInfo.ctorInfo v) => v.type.getUsedConstants | some (ConstantInfo.recInfo v) => v.type.getUsedConstants | some (ConstantInfo.inductInfo v) => v.type.getUsedConstants ++ v.ctors | _ => #[] for c in Std.TreeSet.ofArray consts Name.cmp do if state.result.find? c = some true then msg := msg ++ m!"{MessageData.ofConst (← mkConstWithLevelParams c)} " return msg logInfoAt tk (.joinSep msg.toList "\n")
.lake/packages/batteries/Batteries/Tactic/Trans.lean
module public meta import Lean.Elab.Tactic.ElabTerm public meta section /-! # `trans` tactic This implements the `trans` tactic, which can apply transitivity theorems with an optional middle variable argument. -/ /-- Compose using transitivity, homogeneous case. -/ @[expose] def Trans.simple {r : α → α → Sort _} [Trans r r r] : r a b → r b c → r a c := trans namespace Batteries.Tactic open Lean Meta Elab initialize registerTraceClass `Tactic.trans /-- Environment extension storing transitivity lemmas -/ initialize transExt : SimpleScopedEnvExtension (Name × Array DiscrTree.Key) (DiscrTree Name) ← registerSimpleScopedEnvExtension { addEntry := fun dt (n, ks) => dt.insertCore ks n initial := {} } initialize registerBuiltinAttribute { name := `trans descr := "transitive relation" add := fun decl _ kind => MetaM.run' do let declTy := (← getConstInfo decl).type let (xs, _, targetTy) ← withReducible <| forallMetaTelescopeReducing declTy let fail := throwError "@[trans] attribute only applies to lemmas proving x ∼ y → y ∼ z → x ∼ z, got {indentExpr declTy} with target {indentExpr targetTy}" let .app (.app rel _) _ := targetTy | fail let some yzHyp := xs.back? | fail let some xyHyp := xs.pop.back? | fail let .app (.app _ _) _ ← inferType yzHyp | fail let .app (.app _ _) _ ← inferType xyHyp | fail let key ← withReducible <| DiscrTree.mkPath rel transExt.add (decl, key) kind } open Lean.Elab.Tactic /-- solving `e ← mkAppM' f #[x]` -/ def getExplicitFuncArg? (e : Expr) : MetaM (Option <| Expr × Expr) := do match e with | Expr.app f a => do if ← isDefEq (← mkAppM' f #[a]) e then return some (f, a) else getExplicitFuncArg? f | _ => return none /-- solving `tgt ← mkAppM' rel #[x, z]` given `tgt = f z` -/ def getExplicitRelArg? (tgt f z : Expr) : MetaM (Option <| Expr × Expr) := do match f with | Expr.app rel x => do let check: Bool ← do try let folded ← mkAppM' rel #[x, z] isDefEq folded tgt catch _ => pure false if check then return some (rel, x) else getExplicitRelArg? tgt rel z | _ => return none /-- refining `tgt ← mkAppM' rel #[x, z]` dropping more arguments if possible -/ def getExplicitRelArgCore (tgt rel x z : Expr) : MetaM (Expr × Expr) := do match rel with | Expr.app rel' _ => do let check: Bool ← do try let folded ← mkAppM' rel' #[x, z] isDefEq folded tgt catch _ => pure false if !check then return (rel, x) else getExplicitRelArgCore tgt rel' x z | _ => return (rel ,x) /-- Internal definition for `trans` tactic. Either a binary relation or a non-dependent arrow. -/ inductive TransRelation /-- Expression for transitive relation. -/ | app (rel : Expr) /-- Constant name for transitive relation. -/ | implies (name : Name) (bi : BinderInfo) /-- Finds an explicit binary relation in the argument, if possible. -/ def getRel (tgt : Expr) : MetaM (Option (TransRelation × Expr × Expr)) := do match tgt with | .forallE name binderType body info => return .some (.implies name info, binderType, body) | .app f z => match (← getExplicitRelArg? tgt f z) with | some (rel, x) => let (rel, x) ← getExplicitRelArgCore tgt rel x z return some (.app rel, x, z) | none => return none | _ => return none /-- `trans` applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute [trans]. * `trans s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. * If `s` is omitted, then a metavariable is used instead. Additionally, `trans` also applies to a goal whose target has the form `t → u`, in which case it replaces the goal with `t → s` and `s → u`. -/ elab "trans" t?:(ppSpace colGt term)? : tactic => withMainContext do let tgt := (← instantiateMVars (← (← getMainGoal).getType)).cleanupAnnotations let .some (rel, x, z) ← getRel tgt | throwError (m!"transitivity lemmas only apply to binary relations and " ++ m!"non-dependent arrows, not {indentExpr tgt}") match rel with | .implies name info => -- only consider non-dependent arrows if z.hasLooseBVars then throwError "`trans` is not implemented for dependent arrows{indentExpr tgt}" -- parse the intermeditate term let middleType ← mkFreshExprMVar none let t'? ← t?.mapM (elabTermWithHoles · middleType (← getMainTag)) let middle ← (t'?.map (pure ·.1)).getD (mkFreshExprMVar middleType) liftMetaTactic fun goal => do -- create two new goals let g₁ ← mkFreshExprMVar (some <| .forallE name x middle info) .synthetic let g₂ ← mkFreshExprMVar (some <| .forallE name middle z info) .synthetic -- close the original goal with `fun x => g₂ (g₁ x)` goal.assign (.lam name x (.app g₂ (.app g₁ (.bvar 0))) .default) pure <| [g₁.mvarId!, g₂.mvarId!] ++ if let some (_, gs') := t'? then gs' else [middle.mvarId!] return | .app rel => trace[Tactic.trans]"goal decomposed" trace[Tactic.trans]"rel: {indentExpr rel}" trace[Tactic.trans]"x: {indentExpr x}" trace[Tactic.trans]"z: {indentExpr z}" -- first trying the homogeneous case try let ty ← inferType x let t'? ← t?.mapM (elabTermWithHoles · ty (← getMainTag)) let s ← saveState trace[Tactic.trans]"trying homogeneous case" let lemmas := (← (transExt.getState (← getEnv)).getUnify rel).push ``Trans.simple for lem in lemmas do trace[Tactic.trans]"trying lemma {lem}" try liftMetaTactic fun g => do let lemTy ← inferType (← mkConstWithLevelParams lem) let arity ← withReducible <| forallTelescopeReducing lemTy fun es _ => pure es.size let y ← (t'?.map (pure ·.1)).getD (mkFreshExprMVar ty) let g₁ ← mkFreshExprMVar (some <| ← mkAppM' rel #[x, y]) .synthetic let g₂ ← mkFreshExprMVar (some <| ← mkAppM' rel #[y, z]) .synthetic g.assign (← mkAppOptM lem (.replicate (arity - 2) none ++ #[some g₁, some g₂])) pure <| [g₁.mvarId!, g₂.mvarId!] ++ if let some (_, gs') := t'? then gs' else [y.mvarId!] return catch _ => s.restore pure () catch _ => trace[Tactic.trans]"trying heterogeneous case" let t'? ← t?.mapM (elabTermWithHoles · none (← getMainTag)) let s ← saveState for lem in (← (transExt.getState (← getEnv)).getUnify rel).push ``HEq.trans |>.push ``Trans.trans do try liftMetaTactic fun g => do trace[Tactic.trans]"trying lemma {lem}" let lemTy ← inferType (← mkConstWithLevelParams lem) let arity ← withReducible <| forallTelescopeReducing lemTy fun es _ => pure es.size trace[Tactic.trans]"arity: {arity}" trace[Tactic.trans]"lemma-type: {lemTy}" let y ← (t'?.map (pure ·.1)).getD (mkFreshExprMVar none) trace[Tactic.trans]"obtained y: {y}" trace[Tactic.trans]"rel: {indentExpr rel}" trace[Tactic.trans]"x:{indentExpr x}" trace[Tactic.trans]"z: {indentExpr z}" let g₂ ← mkFreshExprMVar (some <| ← mkAppM' rel #[y, z]) .synthetic trace[Tactic.trans]"obtained g₂: {g₂}" let g₁ ← mkFreshExprMVar (some <| ← mkAppM' rel #[x, y]) .synthetic trace[Tactic.trans]"obtained g₁: {g₁}" g.assign (← mkAppOptM lem (.replicate (arity - 2) none ++ #[some g₁, some g₂])) pure <| [g₁.mvarId!, g₂.mvarId!] ++ if let some (_, gs') := t'? then gs' else [y.mvarId!] return catch e => trace[Tactic.trans]"failed: {e.toMessageData}" s.restore throwError m!"no applicable transitivity lemma found for {indentExpr tgt}" /-- Synonym for `trans` tactic. -/ syntax "transitivity" (ppSpace colGt term)? : tactic set_option hygiene false in macro_rules | `(tactic| transitivity) => `(tactic| trans) | `(tactic| transitivity $e) => `(tactic| trans $e) end Batteries.Tactic
.lake/packages/batteries/Batteries/Tactic/Lemma.lean
module public meta import Lean.Meta.Tactic.TryThis public meta import Lean.Elab.Command public meta section /-! # Control for `lemma` command The `lemma` command exists in `Mathlib`, but not in `Std`. This file enforces the convention by introducing a code-action to replace `lemma` by `theorem`. -/ namespace Batteries.Tactic.Lemma open Lean Elab.Command Meta.Tactic /-- Enables the use of `lemma` as a synonym for `theorem` -/ register_option lang.lemmaCmd : Bool := { defValue := false descr := "enable the use of the `lemma` command as a synonym for `theorem`" } /-- Check whether `lang.lemmaCmd` option is enabled -/ def checkLangLemmaCmd (o : Options) : Bool := o.get `lang.lemmaCmd lang.lemmaCmd.defValue /-- `lemma` is not supported, please use `theorem` instead -/ syntax (name := lemmaCmd) declModifiers group("lemma " declId ppIndent(declSig) declVal) : command /-- Elaborator for the `lemma` command, if the option `lang.lemmaCmd` is false the command emits a warning and code action instructing the user to use `theorem` instead.-/ @[command_elab «lemmaCmd»] def elabLemma : CommandElab := fun stx => do unless checkLangLemmaCmd (← getOptions) do let lemmaStx := stx[1][0] Elab.Command.liftTermElabM <| TryThis.addSuggestion lemmaStx { suggestion := "theorem" } logErrorAt lemmaStx "`lemma` is not supported by default, please use `theorem` instead.\n\ Use `set_option lang.lemmaCmd true` to enable the use of the `lemma` command in a file.\n\ Use the command line option `-Dlang.lemmaCmd=true` to enable the use of `lemma` globally." let out ← Elab.liftMacroM <| do let stx := stx.modifyArg 1 fun stx => let stx := stx.modifyArg 0 (mkAtomFrom · "theorem" (canonical := true)) stx.setKind ``Parser.Command.theorem pure <| stx.setKind ``Parser.Command.declaration Elab.Command.elabCommand out
.lake/packages/batteries/Batteries/Tactic/PrintPrefix.lean
module public meta import Batteries.Lean.Util.EnvSearch public meta import Lean.Elab.Tactic.Config public meta import Lean.Elab.Command public meta section namespace Batteries.Tactic open Lean Elab Command /-- Options to control `#print prefix` command and `getMatchingConstants`. -/ structure PrintPrefixConfig where /-- Include declarations in imported environment. -/ imported : Bool := true /-- Include declarations whose types are propositions. -/ propositions : Bool := true /-- Exclude declarations whose types are not propositions. -/ propositionsOnly : Bool := false /-- Print the type of a declaration. -/ showTypes : Bool := true /-- Include internal declarations (names starting with `_`, `match_` or `proof_`) -/ internals : Bool := false /-- Function elaborating `Config`. -/ declare_command_config_elab elabPrintPrefixConfig PrintPrefixConfig /-- `reverseName name` reverses the components of a name. -/ private def reverseName : Name → (pre : Name := .anonymous) → Name | .anonymous, p => p | .str q s, p => reverseName q (.str p s) | .num q n, p => reverseName q (.num p n) /-- `takeNameSuffix n name` returns a pair `(pre, suf)` where `suf` contains the last `n` components of the name and `pre` contains the rest. -/ private def takeNameSuffix (cnt : Nat) (name : Name) (pre : Name := .anonymous) : Name × Name := match cnt, name with | .succ cnt, .str q s => takeNameSuffix cnt q (.str pre s) | .succ cnt, .num q n => takeNameSuffix cnt q (.num pre n) | _, name => (name, reverseName pre) /-- `matchName opts pre cinfo` returns true if the search options should include the constant. -/ private def matchName (opts : PrintPrefixConfig) (pre : Name) (cinfo : ConstantInfo) : MetaM Bool := do let name := cinfo.name unless (← hasConst name) do -- some compiler decls are not known to the elab env, ignore them return false let preCnt := pre.getNumParts let nameCnt := name.getNumParts if preCnt > nameCnt then return false let (root, post) := takeNameSuffix (nameCnt - preCnt) name if root ≠ pre then return false if !opts.internals && post.isInternalDetail then return false if opts.propositions != opts.propositionsOnly then return opts.propositions let isProp := (Expr.isProp <$> Lean.Meta.inferType cinfo.type) <|> pure false pure <| opts.propositionsOnly == (← isProp) private def lexNameLt : Name -> Name -> Bool | _, .anonymous => false | .anonymous, _ => true | .num p m, .num q n => m < n || m == n && lexNameLt p q | .num _ _, .str _ _ => true | .str _ _, .num _ _ => false | .str p m, .str q n => m < n || m == n && lexNameLt p q private def matchingConstants (opts : PrintPrefixConfig) (pre : Name) : MetaM (Array MessageData) := do let cinfos ← getMatchingConstants (matchName opts pre) opts.imported let cinfos := cinfos.qsort fun p q => lexNameLt (reverseName p.name) (reverseName q.name) cinfos.mapM fun cinfo => do if opts.showTypes then pure <| MessageData.signature cinfo.name ++ "\n" else pure m!"{MessageData.ofConst (← mkConstWithLevelParams cinfo.name)}\n" /-- The command `#print prefix foo` will print all definitions that start with the namespace `foo`. For example, the command below will print out definitions in the `List` namespace: ```lean #print prefix List ``` `#print prefix` can be controlled by flags in `PrintPrefixConfig`. These provide options for filtering names and formatting. For example, `#print prefix` by default excludes internal names, but this can be controlled via config: ```lean #print prefix (config := {internals := true}) List ``` By default, `#print prefix` prints the type after each name. This can be controlled by setting `showTypes` to `false`: ```lean #print prefix (config := {showTypes := false}) List ``` The complete set of flags can be seen in the documentation for `Lean.Elab.Command.PrintPrefixConfig`. -/ elab (name := printPrefix) tk:"#print " colGt "prefix" cfg:Lean.Parser.Tactic.optConfig name:(ident)? : command => do if let some name := name then let opts ← elabPrintPrefixConfig cfg liftTermElabM do let mut msgs ← matchingConstants opts name.getId if msgs.isEmpty then if let [name] ← resolveGlobalConst name then msgs ← matchingConstants opts name logInfoAt tk (.joinSep msgs.toList "")
.lake/packages/batteries/Batteries/Tactic/OpenPrivate.lean
module public meta import Lean.Elab.Command public meta import Lean.Util.FoldConsts public meta import Lean.Parser.Module public meta section open Lean Parser.Tactic Elab Command namespace Lean /-- Collects the names of private declarations referenced in definition `n`. -/ def Meta.collectPrivateIn [Monad m] [MonadEnv m] [MonadError m] (n : Name) (set := NameSet.empty) : m NameSet := do let c ← getConstInfo n let traverse value := Expr.foldConsts value set fun c a => if isPrivateName c then a.insert c else a if let some value := c.value? then return traverse value if let some c := (← getEnv).find? (n ++ `_cstage1) then if let some value := c.value? then return traverse value return traverse c.type /-- Get the module index given a module name. -/ def Environment.moduleIdxForModule? (env : Environment) (mod : Name) : Option ModuleIdx := (env.allImportedModuleNames.idxOf? mod).map fun idx => idx instance : DecidableEq ModuleIdx := instDecidableEqNat /-- Get the list of declarations in a module (referenced by index). -/ def Environment.declsInModuleIdx (env : Environment) (idx : ModuleIdx) : List Name := env.const2ModIdx.fold (fun acc n i => if i = idx then n :: acc else acc) [] /-- Add info to the info tree corresponding to a module name. -/ def Elab.addModuleInfo [Monad m] [MonadInfoTree m] (stx : Ident) : m Unit := do -- HACK: The server looks specifically for ofCommandInfo nodes on `import` syntax -- to do go-to-def for modules, so we have to add something that looks like an import -- to the info tree. (Ideally this would be an `.ofModuleInfo` node instead.) pushInfoLeaf <| .ofCommandInfo { elaborator := `import stx := Unhygienic.run `(Parser.Module.import| import $stx) |>.raw.copyHeadTailInfoFrom stx } namespace Elab.Command /-- Core elaborator for `open private` and `export private`. -/ def elabOpenPrivateLike (ids : Array Ident) (tgts mods : Option (Array Ident)) (f : (priv full user : Name) → CommandElabM Name) : CommandElabM Unit := do let mut names := NameSet.empty for tgt in tgts.getD #[] do let n ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo tgt names ← Meta.collectPrivateIn n names let env ← getEnv for mod in mods.getD #[] do let some modIdx := env.moduleIdxForModule? mod.getId | throwError "unknown module {mod}" addModuleInfo mod for declName in env.declsInModuleIdx modIdx do if isPrivateName declName then names := names.insert declName let appendNames (msg : MessageData) : MessageData := Id.run do let mut msg := msg for c in names do if let some info := env.findConstVal? c then msg := msg ++ m!"{mkConst c (info.levelParams.map mkLevelParam)}\n" else if let some name := privateToUserName? c then msg := msg ++ s!"{name}\n" msg if ids.isEmpty && !names.isEmpty then logInfo (appendNames "found private declarations:\n") let mut decls := #[] for id in ids do let n := id.getId let rec /-- finds private declarations `n ++ suff` where `n` resolves and `n ++ suff` realizes -/ findAll n suff := do let mut found := [] for c in names do if n.isSuffixOf c then let (c', ok) ← if suff.isAnonymous then pure (c, true) else let c' := c ++ suff if (← getEnv).contains c' then pure (c', true) else try liftCoreM (executeReservedNameAction c') pure (c', (← getEnv).containsOnBranch c') catch _ => pure (c', false) if ok then addConstInfo id c' found := c'::found unless found = [] do return found match n with | .str p s => findAll p (Name.mkSimple s ++ suff) | _ => pure [] match ← findAll n .anonymous with | [] => throwError appendNames m!"'{n}' not found in the provided declarations:\n" | [c] => if let some name := privateToUserName? c then let new ← f c name n decls := decls.push (.explicit n new) else unreachable! | found => throwError s!"provided name is ambiguous: found {found.map privateToUserName?}" modifyScope fun scope => Id.run do let mut openDecls := scope.openDecls for decl in decls do openDecls := decl::openDecls { scope with openDecls := openDecls } /-- The command `open private a b c in foo bar` will look for private definitions named `a`, `b`, `c` in declarations `foo` and `bar` and open them in the current scope. This does not make the definitions public, but rather makes them accessible in the current section by the short name `a` instead of the (unnameable) internal name for the private declaration, something like `_private.Other.Module.0.Other.Namespace.foo.a`, which cannot be typed directly because of the `0` name component. It is also possible to specify the module instead with `open private a b c from Other.Module`. -/ syntax (name := openPrivate) "open" ppSpace "private" (ppSpace ident)* (" in" (ppSpace ident)*)? (" from" (ppSpace ident)*)? : command /-- Elaborator for `open private`. -/ @[command_elab openPrivate] def elabOpenPrivate : CommandElab | `(open private $ids* $[in $tgts*]? $[from $mods*]?) => elabOpenPrivateLike ids tgts mods fun c _ _ => pure c | _ => throwUnsupportedSyntax /-- The command `export private a b c in foo bar` is similar to `open private`, but instead of opening them in the current scope it will create public aliases to the private definition. The definition will exist at exactly the original location and name, as if the `private` keyword was not used originally. It will also open the newly created alias definition under the provided short name, like `open private`. It is also possible to specify the module instead with `export private a b c from Other.Module`. -/ syntax (name := exportPrivate) "export" ppSpace "private" (ppSpace ident)* (" in" (ppSpace ident)*)? (" from" (ppSpace ident)*)? : command /-- Elaborator for `export private`. -/ @[command_elab exportPrivate] def elabExportPrivate : CommandElab | `(export private $ids* $[in $tgts*]? $[from $mods*]?) => elabOpenPrivateLike ids tgts mods fun c name _ => liftCoreM do let cinfo ← getConstInfo c if (← getEnv).contains name then throwError s!"'{name}' has already been declared" let decl := Declaration.defnDecl { name := name, levelParams := cinfo.levelParams, type := cinfo.type, value := mkConst c (cinfo.levelParams.map mkLevelParam), hints := ReducibilityHints.abbrev, safety := if cinfo.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } addDecl decl compileDecl decl pure name | _ => throwUnsupportedSyntax
.lake/packages/batteries/Batteries/Tactic/HelpCmd.lean
module public meta import Lean.Elab.Syntax public meta import Lean.DocString public meta import Batteries.Util.LibraryNote public meta section /-! # The `#help` command The `#help` command can be used to list all definitions in a variety of extensible aspects of lean. * `#help option` lists options (used in `set_option myOption`) * `#help attr` lists attributes (used in `@[myAttr] def foo := ...`) * `#help cats` lists syntax categories (like `term`, `tactic`, `stx` etc) * `#help cat C` lists elements of syntax category C * `#help term`, `#help tactic`, `#help conv`, `#help command` are shorthand for `#help cat term` etc. * `#help cat+ C` also shows `elab` and `macro` definitions associated to the syntaxes * `#help note "some note"` lists library notes for which "some note" is a prefix of the label Most forms take an optional identifier to narrow the search; for example `#help option pp` shows only `pp.*` options. However, `#help cat` makes the identifier mandatory, while `#help note` takes a mandatory string literal, rather than an identifier. -/ namespace Batteries.Tactic open Lean Meta Elab Tactic Command /-- The command `#help option` shows all options that have been defined in the current environment. Each option has a format like: ``` option pp.all : Bool := false (pretty printer) display coercions, implicit parameters, proof terms, fully qualified names, universe, and disable beta reduction and notations during pretty printing ``` This says that `pp.all` is an option which can be set to a `Bool` value, and the default value is `false`. If an option has been modified from the default using e.g. `set_option pp.all true`, it will appear as a `(currently: true)` note next to the option. The form `#help option id` will show only options that begin with `id`. -/ syntax withPosition("#help " colGt &"option" (colGt ppSpace Parser.rawIdent)?) : command private def elabHelpOption (id : Option Ident) : CommandElabM Unit := do let id := id.map (·.raw.getId.toString false) let mut decls : Std.TreeMap _ _ compare := {} for (name, decl) in show NameMap OptionDecl from ← getOptionDecls do let name := name.toString false if let some id := id then if !id.isPrefixOf name then continue decls := decls.insert name decl let mut msg := Format.nil let opts ← getOptions if decls.isEmpty then match id with | some id => throwError "no options start with {id}" | none => throwError "no options found (!)" for (name, decl) in decls do let mut msg1 := match decl.defValue with | .ofString val => s!"String := {repr val}" | .ofBool val => s!"Bool := {repr val}" | .ofName val => s!"Name := {repr val}" | .ofNat val => s!"Nat := {repr val}" | .ofInt val => s!"Int := {repr val}" | .ofSyntax val => s!"Syntax := {repr val}" if let some val := opts.find (.mkSimple name) then msg1 := s!"{msg1} (currently: {val})" msg := msg ++ .nest 2 (f!"option {name} : {msg1}" ++ .line ++ decl.descr) ++ .line ++ .line logInfo msg elab_rules : command | `(#help option $(id)?) => elabHelpOption id /-- The command `#help attribute` (or the short form `#help attr`) shows all attributes that have been defined in the current environment. Each attribute has a format like: ``` [inline]: mark definition to always be inlined ``` This says that `inline` is an attribute that can be placed on definitions like `@[inline] def foo := 1`. (Individual attributes may have restrictions on where they can be applied; see the attribute's documentation for details.) Both the attribute's `descr` field as well as the docstring will be displayed here. The form `#help attr id` will show only attributes that begin with `id`. -/ syntax withPosition("#help " colGt (&"attr" <|> &"attribute") (colGt ppSpace Parser.rawIdent)?) : command private def elabHelpAttr (id : Option Ident) : CommandElabM Unit := do let id := id.map (·.raw.getId.toString false) let mut decls : Std.TreeMap _ _ compare := {} /- #adaptation_note On nightly-2024-06-21, added the `.toList` here: without it the requisite `ForIn` instance can't be found. -/ for (name, decl) in (← attributeMapRef.get).toList do let name := name.toString false if let some id := id then if !id.isPrefixOf name then continue decls := decls.insert name decl let mut msg := Format.nil let env ← getEnv if decls.isEmpty then match id with | some id => throwError "no attributes start with {id}" | none => throwError "no attributes found (!)" for (name, decl) in decls do let mut msg1 := s!"[{name}]: {decl.descr}" if let some doc ← findDocString? env decl.ref then msg1 := s!"{msg1}\n{doc.trim}" msg := msg ++ .nest 2 msg1 ++ .line ++ .line logInfo msg elab_rules : command | `(#help attr $(id)?) => elabHelpAttr id | `(#help attribute $(id)?) => elabHelpAttr id /-- Gets the initial string token in a parser description. For example, for a declaration like `syntax "bla" "baz" term : tactic`, it returns `some "bla"`. Returns `none` for syntax declarations that don't start with a string constant. -/ partial def getHeadTk (e : Expr) : Option String := match e.getAppFnArgs with | (``ParserDescr.node, #[_, _, p]) | (``ParserDescr.trailingNode, #[_, _, _, p]) | (``ParserDescr.unary, #[.app _ (.lit (.strVal "withPosition")), p]) | (``ParserDescr.unary, #[.app _ (.lit (.strVal "atomic")), p]) | (``ParserDescr.unary, #[.app _ (.lit (.strVal "ppRealGroup")), p]) | (``ParserDescr.unary, #[.app _ (.lit (.strVal "ppRealFill")), p]) | (``Parser.ppRealFill, #[p]) | (``Parser.withAntiquot, #[_, p]) | (``Parser.leadingNode, #[_, _, p]) | (``Parser.trailingNode, #[_, _, _, p]) | (``Parser.group, #[p]) | (``Parser.withCache, #[_, p]) | (``Parser.withResetCache, #[p]) | (``Parser.withPosition, #[p]) | (``Parser.withOpen, #[p]) | (``Parser.withPositionAfterLinebreak, #[p]) | (``Parser.suppressInsideQuot, #[p]) | (``Parser.ppRealGroup, #[p]) | (``Parser.ppIndent, #[p]) | (``Parser.ppDedent, #[p]) => getHeadTk p | (``ParserDescr.binary, #[.app _ (.lit (.strVal "andthen")), p, q]) | (``HAndThen.hAndThen, #[_, _, _, _, p, .lam _ _ q _]) => getHeadTk p <|> getHeadTk q | (``ParserDescr.nonReservedSymbol, #[.lit (.strVal tk), _]) | (``ParserDescr.symbol, #[.lit (.strVal tk)]) | (``Parser.nonReservedSymbol, #[.lit (.strVal tk), _]) | (``Parser.symbol, #[.lit (.strVal tk)]) | (``Parser.unicodeSymbol, #[.lit (.strVal tk), _]) => pure tk | _ => none /-- The command `#help cats` shows all syntax categories that have been defined in the current environment. Each syntax has a format like: ``` category command [Lean.Parser.initFn✝] ``` The name of the syntax category in this case is `command`, and `Lean.Parser.initFn✝` is the name of the declaration that introduced it. (It is often an anonymous declaration like this, but you can click to go to the definition.) It also shows the doc string if available. The form `#help cats id` will show only syntax categories that begin with `id`. -/ syntax withPosition("#help " colGt &"cats" (colGt ppSpace Parser.rawIdent)?) : command private def elabHelpCats (id : Option Ident) : CommandElabM Unit := do let id := id.map (·.raw.getId.toString false) let mut decls : Std.TreeMap _ _ compare := {} for (name, cat) in (Parser.parserExtension.getState (← getEnv)).categories do let name := name.toString false if let some id := id then if !id.isPrefixOf name then continue decls := decls.insert name cat let mut msg := MessageData.nil let env ← getEnv if decls.isEmpty then match id with | some id => throwError "no syntax categories start with {id}" | none => throwError "no syntax categories found (!)" for (name, cat) in decls do let mut msg1 := m!"category {name} [{mkConst cat.declName}]" if let some doc ← findDocString? env cat.declName then msg1 := msg1 ++ Format.line ++ doc.trim msg := msg ++ .nest 2 msg1 ++ (.line ++ .line : Format) logInfo msg elab_rules : command | `(#help cats $(id)?) => elabHelpCats id /-- The command `#help cat C` shows all syntaxes that have been defined in syntax category `C` in the current environment. Each syntax has a format like: ``` syntax "first"... [Parser.tactic.first] `first | tac | ...` runs each `tac` until one succeeds, or else fails. ``` The quoted string is the leading token of the syntax, if applicable. It is followed by the full name of the syntax (which you can also click to go to the definition), and the documentation. * The form `#help cat C id` will show only attributes that begin with `id`. * The form `#help cat+ C` will also show information about any `macro`s and `elab`s associated to the listed syntaxes. -/ syntax withPosition("#help " colGt &"cat" "+"? colGt ident (colGt ppSpace (Parser.rawIdent <|> str))?) : command private def elabHelpCat (more : Option Syntax) (catStx : Ident) (id : Option String) : CommandElabM Unit := do let mut decls : Std.TreeMap _ _ compare := {} let mut rest : Std.TreeMap _ _ compare := {} let catName := catStx.getId.eraseMacroScopes let some cat := (Parser.parserExtension.getState (← getEnv)).categories.find? catName | throwErrorAt catStx "{catStx} is not a syntax category" liftTermElabM <| Term.addCategoryInfo catStx catName let env ← getEnv for (k, _) in cat.kinds do let mut used := false if let some tk := do getHeadTk (← (← env.find? k).value?) then let tk := tk.trim if let some id := id then if !id.isPrefixOf tk then continue used := true decls := decls.insert tk ((decls.getD tk #[]).push k) if !used && id.isNone then rest := rest.insert (k.toString false) k let mut msg := MessageData.nil if decls.isEmpty && rest.isEmpty then match id with | some id => throwError "no {catName} declarations start with {id}" | none => throwError "no {catName} declarations found" let env ← getEnv let addMsg (k : SyntaxNodeKind) (msg msg1 : MessageData) : CommandElabM MessageData := do let mut msg1 := msg1 if let some doc ← findDocString? env k then msg1 := msg1 ++ Format.line ++ doc.trim msg1 := .nest 2 msg1 if more.isSome then let addElabs {α} (type : String) (attr : KeyedDeclsAttribute α) (msg : MessageData) : CommandElabM MessageData := do let mut msg := msg for e in attr.getEntries env k do let x := e.declName msg := msg ++ Format.line ++ m!"+ {type} {mkConst x}" if let some doc ← findDocString? env x then msg := msg ++ .nest 2 (Format.line ++ doc.trim) pure msg msg1 ← addElabs "macro" macroAttribute msg1 match catName with | `term => msg1 ← addElabs "term elab" Term.termElabAttribute msg1 | `command => msg1 ← addElabs "command elab" commandElabAttribute msg1 | `tactic | `conv => msg1 ← addElabs "tactic elab" tacticElabAttribute msg1 | _ => pure () return msg ++ msg1 ++ (.line ++ .line : Format) for (name, ks) in decls do for k in ks do msg ← addMsg k msg m!"syntax {repr name}... [{mkConst k}]" for (_, k) in rest do msg ← addMsg k msg m!"syntax ... [{mkConst k}]" logInfo msg elab_rules : command | `(#help cat $[+%$more]? $cat) => elabHelpCat more cat none | `(#help cat $[+%$more]? $cat $id:ident) => elabHelpCat more cat (id.getId.toString false) | `(#help cat $[+%$more]? $cat $id:str) => elabHelpCat more cat id.getString /-- format the string to be included in a single markdown bullet -/ def _root_.String.makeBullet (s:String) := "* " ++ ("\n ").intercalate (s.splitOn "\n") open Lean Parser Batteries.Util.LibraryNote in /-- `#help note "foo"` searches for all library notes whose label starts with "foo", then displays those library notes sorted alphabetically by label, grouped by label. The command only displays the library notes that are declared in imported files or in the same file above the line containing the command. -/ elab "#help " colGt &"note" colGt ppSpace name:strLit : command => do let env ← getEnv -- get the library notes from both this and imported files let local_entries := (libraryNoteExt.getEntries env).reverse let imported_entries := (libraryNoteExt.toEnvExtension.getState env).importedEntries -- filter for the appropriate notes while casting to list let label_prefix := name.getString let imported_entries_filtered := imported_entries.flatten.toList.filterMap fun x => if label_prefix.isPrefixOf x.fst then some x else none let valid_entries := imported_entries_filtered ++ local_entries.filterMap fun x => if label_prefix.isPrefixOf x.fst then some x else none let grouped_valid_entries := valid_entries.mergeSort (·.fst ≤ ·.fst) |>.splitBy (·.fst == ·.fst) -- display results in a readable style if grouped_valid_entries.isEmpty then logError "Note not found" else logInfo <| "\n\n".intercalate <| grouped_valid_entries.map fun l => "library_note \"" ++ l.head!.fst ++ "\"\n" ++ "\n\n".intercalate (l.map (·.snd.trim.makeBullet)) /-- The command `#help term` shows all term syntaxes that have been defined in the current environment. See `#help cat` for more information. -/ syntax withPosition("#help " colGt &"term" "+"? (colGt ppSpace (Parser.rawIdent <|> str))?) : command macro_rules | `(#help term%$tk $[+%$more]? $(id)?) => `(#help cat$[+%$more]? $(mkIdentFrom tk `term) $(id)?) /-- The command `#help tactic` shows all tactics that have been defined in the current environment. See `#help cat` for more information. -/ syntax withPosition("#help " colGt &"tactic" "+"? (colGt ppSpace (Parser.rawIdent <|> str))?) : command macro_rules | `(#help tactic%$tk $[+%$more]? $(id)?) => `(#help cat$[+%$more]? $(mkIdentFrom tk `tactic) $(id)?) /-- The command `#help conv` shows all tactics that have been defined in the current environment. See `#help cat` for more information. -/ syntax withPosition("#help " colGt &"conv" "+"? (colGt ppSpace (Parser.rawIdent <|> str))?) : command macro_rules | `(#help conv%$tk $[+%$more]? $(id)?) => `(#help cat$[+%$more]? $(mkIdentFrom tk `conv) $(id)?) /-- The command `#help command` shows all commands that have been defined in the current environment. See `#help cat` for more information. -/ syntax withPosition("#help " colGt &"command" "+"? (colGt ppSpace (Parser.rawIdent <|> str))?) : command macro_rules | `(#help command%$tk $[+%$more]? $(id)?) => `(#help cat$[+%$more]? $(mkIdentFrom tk `command) $(id)?)
.lake/packages/batteries/Batteries/Tactic/ShowUnused.lean
module public meta import Lean.Util.FoldConsts public meta import Lean.Linter.UnusedVariables public meta section /-! # The `#show_unused` command `#show_unused decl1 decl2 ..` will highlight every theorem or definition in the current file not involved in the definition of declarations `decl1`, `decl2`, etc. The result is shown both in the message on `#show_unused`, as well as on the declarations themselves. -/ namespace Batteries.Tactic.ShowUnused open Lean Elab Command variable (env : Environment) in private partial def visit (n : Name) : StateM NameSet Unit := do if (← get).contains n then modify (·.erase n) let rec visitExpr (e : Expr) : StateM NameSet Unit := e.getUsedConstants.forM visit match env.find? n with | some (ConstantInfo.axiomInfo v) => visitExpr v.type | some (ConstantInfo.defnInfo v) => visitExpr v.type *> visitExpr v.value | some (ConstantInfo.thmInfo v) => visitExpr v.type *> visitExpr v.value | some (ConstantInfo.opaqueInfo v) => visitExpr v.type *> visitExpr v.value | some (ConstantInfo.quotInfo _) => pure () | some (ConstantInfo.ctorInfo v) => visitExpr v.type | some (ConstantInfo.recInfo v) => visitExpr v.type | some (ConstantInfo.inductInfo v) => visitExpr v.type *> v.ctors.forM visit | none => pure () /-- `#show_unused decl1 decl2 ..` will highlight every theorem or definition in the current file not involved in the definition of declarations `decl1`, `decl2`, etc. The result is shown both in the message on `#show_unused`, as well as on the declarations themselves. ``` def foo := 1 def baz := 2 def bar := foo #show_unused bar -- highlights `baz` ``` -/ elab tk:"#show_unused" ids:(ppSpace colGt ident)* : command => do let ns ← ids.mapM fun s => liftCoreM <| realizeGlobalConstNoOverloadWithInfo s let env ← getEnv let decls := env.constants.map₂.foldl (fun m n _ => m.insert n) {} let mut unused := #[] let fileMap ← getFileMap for c in ((ns.forM (visit env)).run decls).2 do if let some { selectionRange := range, .. } := declRangeExt.find? env c then unused := unused.push (c, { start := fileMap.ofPosition range.pos stop := fileMap.ofPosition range.endPos }) unused := unused.qsort (·.2.start < ·.2.start) let pos := fileMap.toPosition <| (tk.getPos? <|> (← getRef).getPos?).getD 0 let pfx := m!"#show_unused (line {pos.line}) says:\n" let post := m!" is not used transitively by \ {← ns.mapM (MessageData.ofConst <$> mkConstWithLevelParams ·)}" for (c, range) in unused do logWarningAt (Syntax.ofRange range) <| .tagged Linter.linter.unusedVariables.name <| m!"{pfx}{MessageData.ofConst (← mkConstWithLevelParams c)}{post}" if unused.isEmpty then logInfoAt tk "No unused definitions" else logWarningAt tk <| m!"unused definitions in this file:\n" ++ m!"\n".joinSep (← unused.toList.mapM (toMessageData <$> mkConstWithLevelParams ·.1))
.lake/packages/batteries/Batteries/Tactic/Lint/TypeClass.lean
module public meta import Lean.Meta.Instances public meta import Batteries.Tactic.Lint.Basic public meta section namespace Batteries.Tactic.Lint open Lean Meta /-- Lints for instances with arguments that cannot be filled in, like ``` instance {α β : Type} [Group α] : Mul α where ... ``` -/ @[env_linter] def impossibleInstance : Linter where noErrorsFound := "No instance has arguments that are impossible to infer" errorsFound := "SOME INSTANCES HAVE ARGUMENTS THAT ARE IMPOSSIBLE TO INFER These are arguments that are not instance-implicit and do not appear in another instance-implicit argument or the return type." test declName := do unless ← isInstance declName do return none forallTelescopeReducing (← inferType (← mkConstWithLevelParams declName)) fun args ty => do let argTys ← args.mapM inferType let impossibleArgs ← args.zipIdx.filterMapM fun (arg, i) => do let fv := arg.fvarId! if (← fv.getDecl).binderInfo.isInstImplicit then return none if ty.containsFVar fv then return none if argTys[i+1:].any (·.containsFVar fv) then return none return some m!"argument {i+1} {arg} : {← inferType arg}" if impossibleArgs.isEmpty then return none addMessageContextFull <| .joinSep impossibleArgs.toList ", " /-- A linter for checking if any declaration whose type is not a class is marked as an instance. -/ @[env_linter] def nonClassInstance : Linter where noErrorsFound := "No instances of non-classes" errorsFound := "INSTANCES OF NON-CLASSES" test declName := do if !(← isInstance declName) then return none let info ← getConstInfo declName if !(← isClass? info.type).isSome then return "should not be an instance" return none
.lake/packages/batteries/Batteries/Tactic/Lint/Basic.lean
module public meta import Lean.Structure public meta import Lean.Elab.InfoTree.Main public meta import Lean.Elab.Exception public meta section open Lean Meta namespace Batteries.Tactic.Lint /-! # Basic linter types and attributes This file defines the basic types and attributes used by the linting framework. A linter essentially consists of a function `(declaration : Name) → MetaM (Option MessageData)`, this function together with some metadata is stored in the `Linter` structure. We define two attributes: * `@[env_linter]` applies to a declaration of type `Linter` and adds it to the default linter set. * `@[nolint linterName]` omits the tagged declaration from being checked by the linter with name `linterName`. -/ /-- Returns true if `decl` is an automatically generated declaration. Also returns true if `decl` is an internal name or created during macro expansion. -/ def isAutoDecl (decl : Name) : CoreM Bool := do if decl.hasMacroScopes then return true if decl.isInternal then return true let env ← getEnv if isReservedName env decl then return true if let Name.str n s := decl then if (← isAutoDecl n) then return true if s.startsWith "proof_" || s.startsWith "match_" || s.startsWith "unsafe_" then return true if env.isConstructor n && s ∈ ["injEq", "inj", "sizeOf_spec", "elim", "noConfusion"] then return true if let ConstantInfo.inductInfo _ := (← getEnv).find? n then if s.startsWith "brecOn_" || s.startsWith "below_" then return true if s ∈ [casesOnSuffix, recOnSuffix, brecOnSuffix, belowSuffix, "ndrec", "ndrecOn", "noConfusionType", "noConfusion", "ofNat", "toCtorIdx", "ctorIdx", "ctorElim", "ctorElimType"] then return true if let some _ := isSubobjectField? env n (.mkSimple s) then return true pure false /-- A linting test for the `#lint` command. -/ structure Linter where /-- `test` defines a test to perform on every declaration. It should never fail. Returning `none` signifies a passing test. Returning `some msg` reports a failing test with error `msg`. -/ test : Name → MetaM (Option MessageData) /-- `noErrorsFound` is the message printed when all tests are negative -/ noErrorsFound : MessageData /-- `errorsFound` is printed when at least one test is positive -/ errorsFound : MessageData /-- If `isFast` is false, this test will be omitted from `#lint-`. -/ isFast := true /-- A `NamedLinter` is a linter associated to a particular declaration. -/ structure NamedLinter extends Linter where /-- The name of the named linter. This is just the declaration name without the namespace. -/ name : Name /-- The linter declaration name -/ declName : Name /-- Gets a linter by declaration name. -/ def getLinter (name declName : Name) : CoreM NamedLinter := unsafe return { ← evalConstCheck Linter ``Linter declName with name, declName } /-- Defines the `env_linter` extension for adding a linter to the default set. -/ initialize batteriesLinterExt : PersistentEnvExtension (Name × Bool) (Name × Bool) (NameMap (Name × Bool)) ← let addEntryFn := fun m (n, b) => m.insert (n.updatePrefix .anonymous) (n, b) registerPersistentEnvExtension { mkInitial := pure {} addImportedFn := fun nss => pure <| nss.foldl (init := {}) fun m ns => ns.foldl (init := m) addEntryFn addEntryFn exportEntriesFn := fun es => es.foldl (fun a _ e => a.push e) #[] } /-- Defines the `@[env_linter]` attribute for adding a linter to the default set. The form `@[env_linter disabled]` will not add the linter to the default set, but it will be shown by `#list_linters` and can be selected by the `#lint` command. Linters are named using their declaration names, without the namespace. These must be distinct. -/ syntax (name := env_linter) "env_linter" &" disabled"? : attr initialize registerBuiltinAttribute { name := `env_linter descr := "Use this declaration as a linting test in #lint" add := fun decl stx kind => do let dflt := stx[1].isNone unless kind == .global do throwError "invalid attribute 'env_linter', must be global" let shortName := decl.updatePrefix .anonymous if let some (declName, _) := (batteriesLinterExt.getState (← getEnv)).find? shortName then Elab.addConstInfo stx declName throwError "invalid attribute 'env_linter', linter '{shortName}' has already been declared" let constInfo ← getConstInfo decl unless ← (isDefEq constInfo.type (mkConst ``Linter)).run' do throwError "must have type Linter, got {constInfo.type}" modifyEnv fun env => batteriesLinterExt.addEntry env (decl, dflt) } /-- `@[nolint linterName]` omits the tagged declaration from being checked by the linter with name `linterName`. -/ syntax (name := nolint) "nolint" (ppSpace ident)+ : attr /-- Defines the user attribute `nolint` for skipping `#lint` -/ initialize nolintAttr : ParametricAttribute (Array Name) ← registerParametricAttribute { name := `nolint descr := "Do not report this declaration in any of the tests of `#lint`" getParam := fun _ => fun | `(attr| nolint $[$ids]*) => ids.mapM fun id => withRef id <| do let shortName := id.getId.eraseMacroScopes let some (declName, _) := (batteriesLinterExt.getState (← getEnv)).find? shortName | throwError "linter '{shortName}' not found" Elab.addConstInfo id declName pure shortName | _ => Elab.throwUnsupportedSyntax } /-- Returns true if `decl` should be checked using `linter`, i.e., if there is no `nolint` attribute. -/ def shouldBeLinted [Monad m] [MonadEnv m] (linter : Name) (decl : Name) : m Bool := return !((nolintAttr.getParam? (← getEnv) decl).getD #[]).contains linter
.lake/packages/batteries/Batteries/Tactic/Lint/Simp.lean
module public meta import Lean.Meta.Tactic.Simp.Main public meta import Batteries.Tactic.Lint.Basic public meta import Batteries.Tactic.OpenPrivate public meta import Batteries.Util.LibraryNote import all Lean.Meta.Tactic.Simp.SimpTheorems public meta section open Lean Meta namespace Batteries.Tactic.Lint /-! # Linter for simplification lemmas This files defines several linters that prevent common mistakes when declaring simp lemmas: * `simpNF` checks that the left-hand side of a simp lemma is not simplified by a different lemma. * `simpVarHead` checks that the head symbol of the left-hand side is not a variable. * `simpComm` checks that commutativity lemmas are not marked as simplification lemmas. -/ /-- The data associated to a simp theorem. -/ structure SimpTheoremInfo where /-- The hypotheses of the theorem -/ hyps : Array Expr /-- The thing to replace -/ lhs : Expr /-- The result of replacement -/ rhs : Expr /-- Is this hypothesis a condition that might turn into a `simp` side-goal? i.e. is it a proposition that isn't marked as instance implicit? -/ def isCondition (h : Expr) : MetaM Bool := do let ldecl ← h.fvarId!.getDecl if ldecl.binderInfo.isInstImplicit then return false isProp ldecl.type /-- Runs the continuation on all the simp theorems encoded in the given type. -/ def withSimpTheoremInfos (ty : Expr) (k : SimpTheoremInfo → MetaM α) : MetaM (Array α) := withReducible do let e ← preprocess (← mkSorry ty true) ty (inv := false) (isGlobal := true) e.toArray.mapM fun (_, ty') => do forallTelescopeReducing ty' fun hyps eq => do let some (_, lhs, rhs) := eq.eq? | throwError "not an equality {eq}" k { hyps, lhs, rhs } /-- Checks whether two expressions are equal for the simplifier. That is, they are reducibly-definitional equal, and they have the same head symbol. -/ def isSimpEq (a b : Expr) (whnfFirst := true) : MetaM Bool := withReducible do let a ← if whnfFirst then whnf a else pure a let b ← if whnfFirst then whnf b else pure b if a.getAppFn.constName? != b.getAppFn.constName? then return false isDefEq a b /-- Constructs a message from all the simp theorems encoded in the given type. -/ def checkAllSimpTheoremInfos (ty : Expr) (k : SimpTheoremInfo → MetaM (Option MessageData)) : MetaM (Option MessageData) := do let errors := (← withSimpTheoremInfos ty fun i => do (← k i).mapM addMessageContextFull).filterMap id if errors.isEmpty then return none return MessageData.joinSep errors.toList Format.line /-- Returns true if this is a `@[simp]` declaration. -/ def isSimpTheorem (declName : Name) : MetaM Bool := do pure $ (← getSimpTheorems).lemmaNames.contains (.decl declName) open Lean.Meta.DiscrTree in /-- Returns the list of elements in the discrimination tree. -/ partial def _root_.Lean.Meta.DiscrTree.elements (d : DiscrTree α) : Array α := d.root.foldl (init := #[]) fun arr _ => trieElements arr where /-- Returns the list of elements in the trie. -/ trieElements (arr) | Trie.node vs children => children.foldl (init := arr ++ vs) fun arr (_, child) => trieElements arr child /-- Add message `msg` to any errors thrown inside `k`. -/ def decorateError (msg : MessageData) (k : MetaM α) : MetaM α := do try k catch e => throw (.error e.getRef m!"{msg}\n{e.toMessageData}") /-- Render the list of simp lemmas. -/ def formatLemmas (usedSimps : Simp.UsedSimps) (simpName : String) (higherOrder : Option Bool) : MetaM MessageData := do let mut args := if higherOrder == none then #[] else #[m!"*"] let env ← getEnv for (thm, _) in usedSimps.map.toArray.qsort (·.2 < ·.2) do if let .decl declName := thm then if env.contains declName && declName != ``eq_self then args := args.push m! "{← mkConstWithFreshMVarLevels declName}" let contextual? := if higherOrder == some true then " +contextual" else "" return m!"{simpName}{contextual?} only {args.toList}" /-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/ @[env_linter] def simpNF : Linter where noErrorsFound := "All left-hand sides of simp lemmas are in simp-normal form." errorsFound := "SOME SIMP LEMMAS ARE NOT IN SIMP-NORMAL FORM. see note [simp-normal form] for tips how to debug this. https://leanprover-community.github.io/mathlib_docs/notes.html#simp-normal%20form" test := fun declName => do unless ← isSimpTheorem declName do return none withConfig Elab.Term.setElabConfig do checkAllSimpTheoremInfos (← getConstInfo declName).type fun { lhs, rhs, hyps, .. } => do -- we use `simp [*]` so that simp lemmas with hypotheses apply to themselves -- higher order simp lemmas need `simp +contextual [*]` to be able to apply to themselves let mut simpTheorems ← getSimpTheorems let mut higherOrder := false for h in hyps do if ← isCondition h then simpTheorems ← simpTheorems.add (.fvar h.fvarId!) #[] h if !higherOrder then higherOrder ← forallTelescope (← inferType h) fun hyps _ => hyps.anyM isCondition let ctx ← Simp.mkContext (config := { contextual := higherOrder }) (simpTheorems := #[simpTheorems]) (congrTheorems := ← getSimpCongrTheorems) let isRfl ← isRflTheorem declName let simplify (e : Expr) (ctx : Simp.Context) (stats : Simp.Stats := {}) : MetaM (Simp.Result × Simp.Stats) := do if !isRfl then simp e ctx (stats := stats) else let (e, s) ← dsimp e ctx (stats := stats) return (Simp.Result.mk e .none .true, s) let ({ expr := lhs', proof? := prf1, .. }, prf1Stats) ← decorateError "simplify fails on left-hand side:" <| simplify lhs ctx if prf1Stats.usedTheorems.map.contains (.decl declName) then return none let ({ expr := rhs', .. }, stats) ← decorateError "simplify fails on right-hand side:" <| simplify rhs ctx prf1Stats let lhs'EqRhs' ← isSimpEq lhs' rhs' (whnfFirst := false) let lhsInNF ← isSimpEq lhs' lhs let simpName := if !isRfl then "simp" else "dsimp" if lhs'EqRhs' then if prf1.isNone then return none -- TODO: FP rewriting foo.eq_2 using `simp only [foo]` return m!"\ {simpName} can prove this:\ \n by {← formatLemmas stats.usedTheorems simpName higherOrder}\ \nOne of the lemmas above could be a duplicate.\ \nIf that's not the case try reordering lemmas or adding @[priority]." else if ¬ lhsInNF then return m!"\ Left-hand side simplifies from\ \n {lhs}\ \nto\ \n {lhs'}\ \nusing\ \n {← formatLemmas prf1Stats.usedTheorems simpName higherOrder}\ \nTry to change the left-hand side to the simplified term!" else if lhs == lhs' then let lhsType ← inferType lhs let mut hints := m!"" for h in hyps do let ldecl ← h.fvarId!.getDecl let mut name := ldecl.userName if name.hasMacroScopes then name := sanitizeName name |>.run' { options := ← getOptions } if ← isProp ldecl.type then -- improve the error message if the hypothesis isn't in `simp` normal form let ({ expr := hType', .. }, stats) ← decorateError m!"simplify fails on hypothesis ({name} : {ldecl.type}):" <| simplify ldecl.type (← Simp.Context.mkDefault) unless ← isSimpEq hType' ldecl.type do hints := hints ++ m!"\ \nThe simp lemma may be invalid because hypothesis {name} simplifies from\ \n {ldecl.type}\ \nto\ \n {hType'}\ \nusing\ \n {← formatLemmas stats.usedTheorems simpName none}\ \nTry to change the hypothesis to the simplified term!" else -- improve the error message if the argument can't be filled in by `simp` if !ldecl.binderInfo.isInstImplicit && !lhs.containsFVar h.fvarId! && !lhsType.containsFVar h.fvarId! then hints := hints ++ m!"\ \nThe simp lemma is invalid because the value of argument\ \n {name} : {ldecl.type}\ \ncannot be inferred by `simp`." return m!"\ Left-hand side does not simplify, when using the simp lemma on itself. \nThis usually means that it will never apply.{hints}\n" else return none library_note "simp-normal form" /-- This note gives you some tips to debug any errors that the simp-normal form linter raises. The reason that a lemma was considered faulty is because its left-hand side is not in simp-normal form. These lemmas are hence never used by the simplifier. This linter gives you a list of other simp lemmas: look at them! Here are some tips depending on the error raised by the linter: 1. 'the left-hand side reduces to XYZ': you should probably use XYZ as the left-hand side. 2. 'simp can prove this': This typically means that lemma is a duplicate, or is shadowed by another lemma: 2a. Always put more general lemmas after specific ones: ``` @[simp] lemma zero_add_zero : 0 + 0 = 0 := rfl @[simp] lemma add_zero : x + 0 = x := rfl ``` And not the other way around! The simplifier always picks the last matching lemma. 2b. You can also use `@[priority]` instead of moving simp-lemmas around in the file. Tip: the default priority is 1000. Use `@[priority 1100]` instead of moving a lemma down, and `@[priority 900]` instead of moving a lemma up. 2c. Conditional simp lemmas are tried last. If they are shadowed just remove the `simp` attribute. 2d. If two lemmas are duplicates, the linter will complain about the first one. Try to fix the second one instead! (You can find it among the other simp lemmas the linter prints out!) 3. 'try_for tactic failed, timeout': This typically means that there is a loop of simp lemmas. Try to apply squeeze_simp to the right-hand side (removing this lemma from the simp set) to see what lemmas might be causing the loop. Another trick is to `set_option trace.simplify.rewrite true` and then apply `try_for 10000 { simp }` to the right-hand side. You will see a periodic sequence of lemma applications in the trace message. -/ /-- A linter for simp lemmas whose lhs has a variable as head symbol, and which hence never fire. -/ @[env_linter] def simpVarHead : Linter where noErrorsFound := "No left-hand sides of a simp lemma has a variable as head symbol." errorsFound := "LEFT-HAND SIDE HAS VARIABLE AS HEAD SYMBOL. Some simp lemmas have a variable as head symbol of the left-hand side (after whnfR):" test := fun declName => do unless ← isSimpTheorem declName do return none checkAllSimpTheoremInfos (← getConstInfo declName).type fun {lhs, ..} => do let lhs ← whnfR lhs let headSym := lhs.getAppFn unless headSym.isFVar do return none return m!"Left-hand side has variable as head symbol: {headSym}" private def Expr.eqOrIff? : Expr → Option (Expr × Expr) | .app (.app (.app (.const ``Eq _) _) lhs) rhs | .app (.app (.const ``Iff _) lhs) rhs => (lhs, rhs) | _ => none /-- A linter for commutativity lemmas that are marked simp. -/ @[env_linter] def simpComm : Linter where noErrorsFound := "No commutativity lemma is marked simp." errorsFound := "COMMUTATIVITY LEMMA IS SIMP. Some commutativity lemmas are simp lemmas:" test := fun declName => withSimpGlobalConfig do withReducible do unless ← isSimpTheorem declName do return none let ty := (← getConstInfo declName).type forallTelescopeReducing ty fun _ ty' => do let some (lhs, rhs) := ty'.eqOrIff? | return none unless lhs.getAppFn.constName? == rhs.getAppFn.constName? do return none let (_, _, ty') ← forallMetaTelescopeReducing ty let some (lhs', rhs') := ty'.eqOrIff? | return none unless ← isDefEq rhs lhs' do return none unless ← withNewMCtxDepth (isDefEq rhs lhs') do return none -- make sure that the discrimination tree will actually find this match (see #69) if (← (← DiscrTree.empty.insert rhs ()).getMatch lhs').isEmpty then return none -- ensure that the second application makes progress: if ← isDefEq lhs' rhs' then return none pure m!"should not be marked simp"
.lake/packages/batteries/Batteries/Tactic/Lint/Frontend.lean
module public meta import Lean.Elab.Command public meta import Batteries.Tactic.Lint.Basic public meta section /-! # Linter frontend and commands This file defines the linter commands which spot common mistakes in the code. * `#lint`: check all declarations in the current file * `#lint in Pkg`: check all declarations in the package `Pkg` (so excluding core or other projects, and also excluding the current file) * `#lint in all`: check all declarations in the environment (the current file and all imported files) For a list of default / non-default linters, see the "Linting Commands" user command doc entry. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint* in Batteries`) to omit the slow tests. You can append a `-` to any command (e.g. `#lint- in Batteries`) to run a silent lint that suppresses the output if all checks pass. A silent lint will fail if any test fails. You can append a `+` to any command (e.g. `#lint+ in Batteries`) to run a verbose lint that reports the result of each linter, including the successes. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments in Batteries` You can add custom linters by defining a term of type `Linter` with the `@[env_linter]` attribute. A linter defined with the name `Batteries.Tactic.Lint.myNewCheck` can be run with `#lint myNewCheck` or `#lint only myNewCheck`. If you add the attribute `@[env_linter disabled]` to `linter.myNewCheck` it will be registered, but not run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ namespace Batteries.Tactic.Lint open Lean Elab Command /-- Verbosity for the linter output. -/ inductive LintVerbosity /-- `low`: only print failing checks, print nothing on success. -/ | low /-- `medium`: only print failing checks, print confirmation on success. -/ | medium /-- `high`: print output of every check. -/ | high deriving Inhabited, DecidableEq, Repr /-- `getChecks slow runOnly runAlways` produces a list of linters. `runOnly` is an optional list of names that should resolve to declarations with type `NamedLinter`. If populated, only these linters are run (regardless of the default configuration). `runAlways` is an optional list of names that should resolve to declarations with type `NamedLinter`. If populated, these linters are always run (regardless of their configuration). Specifying a linter in `runAlways` but not `runOnly` is an error. Otherwise, it uses all enabled linters in the environment tagged with `@[env_linter]`. If `slow` is false, it only uses the fast default tests. -/ def getChecks (slow : Bool) (runOnly : Option (List Name)) (runAlways : Option (List Name)) : CoreM (Array NamedLinter) := do let mut result := #[] for (name, declName, default) in batteriesLinterExt.getState (← getEnv) do let shouldRun := match (runOnly, runAlways) with | (some only, some always) => only.contains name && (always.contains name || default) | (some only, none) => only.contains name | (none, some always) => default || always.contains name | _ => default if shouldRun then let linter ← getLinter name declName if slow || linter.isFast then let _ := Inhabited.mk linter result := result.binInsert (·.name.lt ·.name) linter pure result /-- Runs all the specified linters on all the specified declarations in parallel, producing a list of results. -/ def lintCore (decls : Array Name) (linters : Array NamedLinter) : CoreM (Array (NamedLinter × Std.HashMap Name MessageData)) := do let env ← getEnv let options ← getOptions -- TODO: sanitize options? let tasks : Array (NamedLinter × Array (Name × Task (Option MessageData))) ← linters.mapM fun linter => do let decls ← decls.filterM (shouldBeLinted linter.name) (linter, ·) <$> decls.mapM fun decl => (decl, ·) <$> do BaseIO.asTask do match ← withCurrHeartbeats (linter.test decl) |>.run' mkMetaContext -- We use the context used by `Command.liftTermElabM` |>.run' {options, fileName := "", fileMap := default} {env} |>.toBaseIO with | Except.ok msg? => pure msg? | Except.error err => pure m!"LINTER FAILED:\n{err.toMessageData}" tasks.mapM fun (linter, decls) => do let mut msgs : Std.HashMap Name MessageData := {} for (declName, msg?) in decls do if let some msg := msg?.get then msgs := msgs.insert declName msg pure (linter, msgs) /-- Sorts a map with declaration keys as names by line number. -/ def sortResults (results : Std.HashMap Name α) : CoreM <| Array (Name × α) := do let mut key : Std.HashMap Name Nat := {} for (n, _) in results.toArray do if let some range ← findDeclarationRanges? n then key := key.insert n <| range.range.pos.line pure $ results.toArray.qsort fun (a, _) (b, _) => key.getD a 0 < key.getD b 0 /-- Formats a linter warning as `#check` command with comment. -/ def printWarning (declName : Name) (warning : MessageData) (useErrorFormat : Bool := false) (filePath : System.FilePath := default) : CoreM MessageData := do if useErrorFormat then if let some range ← findDeclarationRanges? declName then let msg ← addMessageContextPartial m!"{filePath}:{range.range.pos.line}:{range.range.pos.column + 1}: error: { ← mkConstWithLevelParams declName} {warning}" return msg addMessageContextPartial m!"#check {← mkConstWithLevelParams declName} /- {warning} -/" /-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/ def printWarnings (results : Std.HashMap Name MessageData) (filePath : System.FilePath := default) (useErrorFormat : Bool := false) : CoreM MessageData := do (MessageData.joinSep ·.toList Format.line) <$> (← sortResults results).mapM fun (declName, warning) => printWarning declName warning (useErrorFormat := useErrorFormat) (filePath := filePath) /-- Formats a map of linter warnings grouped by filename with `-- filename` comments. The first `drop_fn_chars` characters are stripped from the filename. -/ def groupedByFilename (results : Std.HashMap Name MessageData) (useErrorFormat : Bool := false) : CoreM MessageData := do let sp ← if useErrorFormat then getSrcSearchPath else pure {} let grouped : Std.HashMap Name (System.FilePath × Std.HashMap Name MessageData) ← results.foldM (init := {}) fun grouped declName msg => do let mod ← findModuleOf? declName let mod := mod.getD (← getEnv).mainModule grouped.insert mod <$> match grouped[mod]? with | some (fp, msgs) => pure (fp, msgs.insert declName msg) | none => do let fp ← if useErrorFormat then pure <| (← sp.findWithExt "lean" mod).getD (modToFilePath "." mod "lean") else pure default pure (fp, .insert {} declName msg) let grouped' := grouped.toArray.qsort fun (a, _) (b, _) => toString a < toString b (MessageData.joinSep · (Format.line ++ Format.line)) <$> grouped'.toList.mapM fun (mod, fp, msgs) => do pure m!"-- {mod}\n{← printWarnings msgs (filePath := fp) (useErrorFormat := useErrorFormat)}" /-- Formats the linter results as Lean code with comments and `#check` commands. -/ def formatLinterResults (results : Array (NamedLinter × Std.HashMap Name MessageData)) (decls : Array Name) (groupByFilename : Bool) (whereDesc : String) (runSlowLinters : Bool) (verbose : LintVerbosity) (numLinters : Nat) (useErrorFormat : Bool := false) : CoreM MessageData := do let formattedResults ← results.filterMapM fun (linter, results) => do if !results.isEmpty then let warnings ← if groupByFilename || useErrorFormat then groupedByFilename results (useErrorFormat := useErrorFormat) else printWarnings results pure $ some m!"/- The `{linter.name}` linter reports:\n{linter.errorsFound} -/\n{warnings}\n" else if verbose = LintVerbosity.high then pure $ some m!"/- OK: {linter.noErrorsFound} -/" else pure none let mut s := MessageData.joinSep formattedResults.toList Format.line let numAutoDecls := (← decls.filterM isAutoDecl).size let failed := results.map (·.2.size) |>.foldl (·+·) 0 unless verbose matches LintVerbosity.low do s := m!"-- Found {failed} error{if failed == 1 then "" else "s" } in {decls.size - numAutoDecls} declarations (plus { numAutoDecls} automatically generated ones) {whereDesc } with {numLinters} linters\n\n{s}" unless runSlowLinters do s := m!"{s}-- (slow linters skipped)\n" pure s /-- Get the list of declarations in the current module. -/ def getDeclsInCurrModule : CoreM (Array Name) := do pure $ (← getEnv).constants.map₂.foldl (init := #[]) fun r k _ => r.push k /-- Get the list of all declarations in the environment. -/ def getAllDecls : CoreM (Array Name) := do pure $ (← getEnv).constants.map₁.fold (init := ← getDeclsInCurrModule) fun r k _ => r.push k /-- Get the list of all declarations in the specified package. -/ def getDeclsInPackage (pkg : Name) : CoreM (Array Name) := do let env ← getEnv let mut decls ← getDeclsInCurrModule let modules := env.header.moduleNames.map (pkg.isPrefixOf ·) return env.constants.map₁.fold (init := decls) fun decls declName _ => if modules[env.const2ModIdx[declName]?.get! (α := Nat)]! then decls.push declName else decls /-- The `in foo` config argument allows running the linter on a specified project. -/ syntax inProject := " in " ident open Elab Command in /-- The command `#lint` runs the linters on the current file (by default). `#lint only someLinter` can be used to run only a single linter. -/ elab tk:"#lint" verbosity:("+" <|> "-")? fast:"*"? only:(&" only")? linters:(ppSpace ident)* project:(inProject)? : command => do let (decls, whereDesc, groupByFilename) ← match project with | none => do pure (← liftCoreM getDeclsInCurrModule, "in the current file", false) | some cfg => match cfg with | `(inProject| in $id) => let id := id.getId.eraseMacroScopes if id == `all then pure (← liftCoreM getAllDecls, "in all files", true) else pure (← liftCoreM (getDeclsInPackage id), s!"in {id}", true) | _ => throwUnsupportedSyntax let verbosity : LintVerbosity ← match verbosity with | none => pure .medium | some ⟨.node _ `token.«+» _⟩ => pure .high | some ⟨.node _ `token.«-» _⟩ => pure .low | _ => throwUnsupportedSyntax let fast := fast.isSome let onlyNames : Option (List Name) := match only.isSome with | true => some (linters.map fun l => l.getId).toList | false => none let linters ← liftCoreM do let mut result ← getChecks (slow := !fast) (runOnly := onlyNames) none let linterState := batteriesLinterExt.getState (← getEnv) for id in linters do let name := id.getId.eraseMacroScopes let some (declName, _) := linterState.find? name | throwErrorAt id "not a linter: {name}" Elab.addConstInfo id declName let linter ← getLinter name declName result := result.binInsert (·.name.lt ·.name) linter pure result let results ← liftCoreM <| lintCore decls linters let failed := results.any (!·.2.isEmpty) let mut fmtResults ← liftCoreM <| formatLinterResults results decls (groupByFilename := groupByFilename) whereDesc (runSlowLinters := !fast) verbosity linters.size if failed then logError fmtResults else if verbosity != LintVerbosity.low then logInfoAt tk m!"{fmtResults}\n-- All linting checks passed!" open Elab Command in /-- The command `#list_linters` prints a list of all available linters. -/ elab "#list_linters" : command => do let mut result := #[] for (name, _, dflt) in batteriesLinterExt.getState (← getEnv) do result := result.binInsert (·.1.lt ·.1) (name, dflt) let mut msg := m!"Available linters (linters marked with (*) are in the default lint set):" for (name, dflt) in result do msg := msg ++ m!"\n{name}{if dflt then " (*)" else ""}" logInfo msg
.lake/packages/batteries/Batteries/Tactic/Lint/Misc.lean
module public meta import Lean.Util.CollectLevelParams public meta import Lean.Util.ForEachExpr public meta import Lean.Meta.GlobalInstances public meta import Lean.Meta.Check public meta import Lean.Util.Recognizers public meta import Lean.DocString public meta import Batteries.Tactic.Lint.Basic public meta section open Lean Meta Std namespace Batteries.Tactic.Lint /-! # Various linters This file defines several small linters. -/ /-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/ @[env_linter] def dupNamespace : Linter where noErrorsFound := "No declarations have a duplicate namespace." errorsFound := "DUPLICATED NAMESPACES IN NAME:" test declName := do if ← isAutoDecl declName then return none if isGlobalInstance (← getEnv) declName then return none let nm := declName.components let some (dup, _) := nm.zip nm.tail! |>.find? fun (x, y) => x == y | return none return m!"The namespace {dup} is duplicated in the name" /-- A linter for checking for unused arguments. We skip all declarations that contain `sorry` in their value. -/ @[env_linter] def unusedArguments : Linter where noErrorsFound := "No unused arguments." errorsFound := "UNUSED ARGUMENTS." test declName := do if ← isAutoDecl declName then return none if ← isProjectionFn declName then return none let info ← getConstInfo declName let ty := info.type let some val := info.value? | return none if val.hasSorry || ty.hasSorry then return none forallTelescope ty fun args ty => do let mut e := (mkAppN val args).headBeta e := mkApp e ty for arg in args do let ldecl ← getFVarLocalDecl arg e := mkApp e ldecl.type if let some val := ldecl.value? then e := mkApp e val let unused := args.zip (.range args.size) |>.filter fun (arg, _) => !e.containsFVar arg.fvarId! if unused.isEmpty then return none addMessageContextFull <| .joinSep (← unused.toList.mapM fun (arg, i) => return m!"argument {i+1} {arg} : {← inferType arg}") m!", " /-- A linter for checking definition doc strings. -/ @[env_linter] def docBlame : Linter where noErrorsFound := "No definitions are missing documentation." errorsFound := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS:" test declName := do if (← isAutoDecl declName) || isGlobalInstance (← getEnv) declName then return none -- FIXME: scoped/local instances should also not be linted if let .str p _ := declName then if isGlobalInstance (← getEnv) p then -- auxillary functions for instances should not be linted return none if let .str _ s := declName then if s == "parenthesizer" || s == "formatter" || s == "delaborator" || s == "quot" then return none let kind ← match ← getConstInfo declName with | .axiomInfo .. => pure "axiom" | .opaqueInfo .. => pure "constant" | .defnInfo info => -- leanprover/lean4#2575: -- projections are generated as `def`s even when they should be `theorem`s if ← isProjectionFn declName <&&> isProp info.type then return none pure "definition" | .inductInfo .. => pure "inductive" | _ => return none let (none) ← findDocString? (← getEnv) declName | return none return m!"{kind} missing documentation string" /-- A linter for checking theorem doc strings. -/ @[env_linter disabled] def docBlameThm : Linter where noErrorsFound := "No theorems are missing documentation." errorsFound := "THEOREMS ARE MISSING DOCUMENTATION STRINGS:" test declName := do if ← isAutoDecl declName then return none let kind ← match ← getConstInfo declName with | .thmInfo .. => pure "theorem" | .defnInfo info => -- leanprover/lean4#2575: -- projections are generated as `def`s even when they should be `theorem`s if ← isProjectionFn declName <&&> isProp info.type then pure "Prop projection" else return none | _ => return none let (none) ← findDocString? (← getEnv) declName | return none return m!"{kind} missing documentation string" /-- A linter for checking whether the correct declaration constructor (definition or theorem) has been used. -/ @[env_linter] def defLemma : Linter where noErrorsFound := "All declarations correctly marked as def/lemma." errorsFound := "INCORRECT DEF/LEMMA:" test declName := do if (← isAutoDecl declName) || isGlobalInstance (← getEnv) declName then return none -- leanprover/lean4#2575: -- projections are generated as `def`s even when they should be `theorem`s if ← isProjectionFn declName then return none let info ← getConstInfo declName let isThm ← match info with | .defnInfo .. => pure false | .thmInfo .. => pure true | _ => return none match isThm, ← isProp info.type with | true, false => pure "is a lemma/theorem, should be a def" | false, true => pure "is a def, should be lemma/theorem" | _, _ => return none /-- A linter for checking whether statements of declarations are well-typed. -/ @[env_linter] def checkType : Linter where noErrorsFound := "The statements of all declarations type-check with default reducibility settings." errorsFound := "THE STATEMENTS OF THE FOLLOWING DECLARATIONS DO NOT TYPE-CHECK." isFast := true test declName := do if ← isAutoDecl declName then return none if ← isTypeCorrect (← getConstInfo declName).type then return none return m!"the statement doesn't type check." /-- `univParamsGrouped e` computes for each `level` `u` of `e` the parameters that occur in `u`, and returns the corresponding set of lists of parameters. In pseudo-mathematical form, this returns `{{p : parameter | p ∈ u} | (u : level) ∈ e}` FIXME: We use `Array Name` instead of `HashSet Name`, since `HashSet` does not have an equality instance. It will ignore `nm₀.proof_i` declarations. -/ private def univParamsGrouped (e : Expr) (nm₀ : Name) : Std.HashSet (Array Name) := runST fun σ => do let res ← ST.mkRef (σ := σ) {} e.forEach fun | .sort u => res.modify (·.insert (CollectLevelParams.visitLevel u {}).params) | .const n us => do if let .str n s .. := n then if n == nm₀ && s.startsWith "proof_" then return res.modify <| us.foldl (·.insert <| CollectLevelParams.visitLevel · {} |>.params) | _ => pure () res.get /-- The good parameters are the parameters that occur somewhere in the set as a singleton or (recursively) with only other good parameters. All other parameters in the set are bad. -/ private partial def badParams (l : Array (Array Name)) : Array Name := let goodLevels := l.filterMap fun | #[u] => some u | _ => none if goodLevels.isEmpty then l.flatten.toList.eraseDups.toArray else badParams <| l.map (·.filter (!goodLevels.contains ·)) /-- A linter for checking that there are no bad `max u v` universe levels. Checks whether all universe levels `u` in the type of `d` are "good". This means that `u` either occurs in a `level` of `d` by itself, or (recursively) with only other good levels. When this fails, usually this means that there is a level `max u v`, where neither `u` nor `v` occur by themselves in a level. It is ok if *one* of `u` or `v` never occurs alone. For example, `(α : Type u) (β : Type (max u v))` is a occasionally useful method of saying that `β` lives in a higher universe level than `α`. -/ @[env_linter] def checkUnivs : Linter where noErrorsFound := "All declarations have good universe levels." errorsFound := "THE STATEMENTS OF THE FOLLOWING DECLARATIONS HAVE BAD UNIVERSE LEVELS. \ This usually means that there is a `max u v` in the type where neither `u` nor `v` \ occur by themselves. Solution: Find the type (or type bundled with data) that has this \ universe argument and provide the universe level explicitly. If this happens in an implicit \ argument of the declaration, a better solution is to move this argument to a `variables` \ command (then it's not necessary to provide the universe level).\n\n\ It is possible that this linter gives a false positive on definitions where the value of the \ definition has the universes occur separately, and the definition will usually be used with \ explicit universe arguments. In this case, feel free to add `@[nolint checkUnivs]`." isFast := true test declName := do if ← isAutoDecl declName then return none let bad := badParams (univParamsGrouped (← getConstInfo declName).type declName).toArray if bad.isEmpty then return none return m!"universes {bad} only occur together." /-- A linter for checking that declarations aren't syntactic tautologies. Checks whether a lemma is a declaration of the form `∀ a b ... z, e₁ = e₂` where `e₁` and `e₂` are identical exprs. We call declarations of this form syntactic tautologies. Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving basic facts with rfl when elaboration results in a different term than the user intended. -/ @[env_linter] def synTaut : Linter where noErrorsFound := "No declarations are syntactic tautologies." errorsFound := "THE FOLLOWING DECLARATIONS ARE SYNTACTIC TAUTOLOGIES. \ This usually means that they are of the form `∀ a b ... z, e₁ = e₂` where `e₁` and `e₂` are \ identical expressions. We call declarations of this form syntactic tautologies. \ Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving \ basic facts using `rfl`, when elaboration results in a different term than the user intended. \ You should check that the declaration really says what you think it does." isFast := true test declName := do if ← isAutoDecl declName then return none forallTelescope (← getConstInfo declName).type fun _ ty => do let some (lhs, rhs) := ty.eq?.map (fun (_, l, r) => (l, r)) <|> ty.iff? | return none if lhs == rhs then return m!"LHS equals RHS syntactically" return none /-- Return a list of unused `let_fun` terms in an expression that introduce proofs. -/ @[nolint unusedArguments] def findUnusedHaves (_ : Expr) : MetaM (Array MessageData) := do -- adaptation note: kmill 2025-06-29. `Expr.letFun?` is deprecated. -- This linter needs to be updated for `Expr.letE (nondep := true)`, but it has false -- positives, so I am disabling it for now. return #[] /- let res ← IO.mkRef #[] forEachExpr e fun e => do match e.letFun? with | some (n, t, _, b) => if n.isInternal then return if b.hasLooseBVars then return unless ← Meta.isProp t do return let msg ← addMessageContextFull m!"unnecessary have {n.eraseMacroScopes} : {t}" res.modify (·.push msg) | _ => return res.get -/ /-- A linter for checking that declarations don't have unused term mode have statements. -/ @[env_linter] def unusedHavesSuffices : Linter where noErrorsFound := "No declarations have unused term mode have statements." errorsFound := "THE FOLLOWING DECLARATIONS HAVE INEFFECTUAL TERM MODE HAVE/SUFFICES BLOCKS. \ In the case of `have` this is a term of the form `have h := foo, bar` where `bar` does not \ refer to `foo`. Such statements have no effect on the generated proof, and can just be \ replaced by `bar`, in addition to being ineffectual, they may make unnecessary assumptions \ in proofs appear as if they are used. \ For `suffices` this is a term of the form `suffices h : foo, proof_of_goal, proof_of_foo` \ where `proof_of_goal` does not refer to `foo`. \ Such statements have no effect on the generated proof, and can just be replaced by \ `proof_of_goal`, in addition to being ineffectual, they may make unnecessary assumptions \ in proofs appear as if they are used." test declName := do if ← isAutoDecl declName then return none let info ← getConstInfo declName let mut unused ← findUnusedHaves info.type if let some value := info.value? then unused := unused ++ (← findUnusedHaves value) unless unused.isEmpty do return some <| .joinSep unused.toList ", " return none /-- A linter for checking if variables appearing on both sides of an iff are explicit. Ideally, such variables should be implicit instead. -/ @[env_linter disabled] def explicitVarsOfIff : Linter where noErrorsFound := "No explicit variables on both sides of iff" errorsFound := "EXPLICIT VARIABLES ON BOTH SIDES OF IFF" test declName := do if ← isAutoDecl declName then return none forallTelescope (← getConstInfo declName).type fun args ty => do let some (lhs, rhs) := ty.iff? | return none let explicit ← args.filterM fun arg => return (← getFVarLocalDecl arg).binderInfo.isExplicit && lhs.containsFVar arg.fvarId! && rhs.containsFVar arg.fvarId! if explicit.isEmpty then return none addMessageContextFull m!"should be made implicit: { MessageData.joinSep (explicit.toList.map (m!"{·}")) ", "}"
.lake/packages/batteries/Batteries/Lean/LawfulMonad.lean
module public import Lean.Elab.Command @[expose] public section /-! # Construct `LawfulMonad` instances for the Lean monad stack. -/ open Lean Elab Term Tactic Command instance : LawfulMonad (EIO ε) := inferInstanceAs <| LawfulMonad (EStateM _ _) instance : LawfulMonad BaseIO := inferInstanceAs <| LawfulMonad (EIO _) instance : LawfulMonad IO := inferInstanceAs <| LawfulMonad (EIO _) instance : LawfulMonad (EST ε σ) := inferInstanceAs <| LawfulMonad (EStateM _ _) instance : LawfulMonad CoreM := inferInstanceAs <| LawfulMonad (ReaderT _ <| StateRefT' _ _ (EIO Exception)) instance : LawfulMonad MetaM := inferInstanceAs <| LawfulMonad (ReaderT _ <| StateRefT' _ _ CoreM) instance : LawfulMonad TermElabM := inferInstanceAs <| LawfulMonad (ReaderT _ <| StateRefT' _ _ MetaM) instance : LawfulMonad TacticM := inferInstanceAs <| LawfulMonad (ReaderT _ $ StateRefT' _ _ $ TermElabM) instance : LawfulMonad CommandElabM := inferInstanceAs <| LawfulMonad (ReaderT _ $ StateRefT' _ _ $ EIO _)
.lake/packages/batteries/Batteries/Lean/Float.lean
/- Copyright (c) 2023 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ module @[expose] public section namespace Float /-- The floating point value "positive infinity", also used to represent numerical computations which produce finite values outside of the representable range of `Float`. -/ def inf : Float := 1/0 /-- The floating point value "not a number", used to represent erroneous numerical computations such as `0 / 0`. Using `nan` in any float operation will return `nan`, and all comparisons involving `nan` return `false`, including in particular `nan == nan`. -/ def nan : Float := 0/0 /-- Returns `v, exp` integers such that `f = v * 2^exp`. (`e` is not minimal, but `v.abs` will be at most `2^53 - 1`.) Returns `none` when `f` is not finite (i.e. `inf`, `-inf` or a `nan`). -/ def toRatParts (f : Float) : Option (Int × Int) := if f.isFinite then let (f', exp) := f.frExp let x := (2^53:Nat).toFloat * f' let v := if x < 0 then (-(-x).floor.toUInt64.toNat : Int) else (x.floor.toUInt64.toNat : Int) some (v, exp - 53) else none /-- Returns `v, exp` integers such that `f = v * 2^exp`. Like `toRatParts`, but `e` is guaranteed to be minimal (`n` is always odd), unless `n = 0`. `n.abs` will be at most `2^53 - 1` because `Float` has 53 bits of precision. Returns `none` when `f` is not finite (i.e. `inf`, `-inf` or a `nan`). -/ partial def toRatParts' (f : Float) : Option (Int × Int) := f.toRatParts.map fun (n, e) => if n == 0 then (0, 0) else let neg : Bool := n < 0 let v := n.natAbs.toUInt64 let c := trailingZeros v 0 let v := (v >>> c.toUInt64).toNat (if neg then -v else v, e + c.toNat) where /-- Calculates the number of trailing bits in a `UInt64`. Requires `v ≠ 0`. -/ -- Note: it's a bit dumb to be using a loop here, but it is hopefully written -- such that LLVM can tell we are computing trailing bits and do good things to it -- TODO: prove termination under suitable assumptions (only relevant if `Float` is not opaque) trailingZeros (v : UInt64) (c : UInt8) := if v &&& 1 == 0 then trailingZeros (v >>> 1) (c + 1) else c /-- Converts `f` to a string, including all decimal digits. -/ def toStringFull (f : Float) : String := if let some (v, exp) := toRatParts f then let v' := v.natAbs let s := if exp ≥ 0 then Nat.repr (v' * (2^exp.toNat:Nat)) else let e := (-exp).toNat let intPart := v' / 2^e let rem := v' % 2^e if rem == 0 then Nat.repr intPart else let rem := Nat.repr ((2^e + v' % 2^e) * 5^e) let rem := rem.dropRightWhile (· == '0') s!"{intPart}.{String.Pos.Raw.extract rem ⟨1⟩ rem.endPos}" if v < 0 then s!"-{s}" else s else f.toString -- inf, -inf, nan end Float /-- Divide two natural numbers, to produce a correctly rounded (nearest-ties-to-even) `Float` result. -/ protected def Nat.divFloat (a b : Nat) : Float := if b = 0 then if a = 0 then Float.nan else Float.inf else let ea := a.log2 let eb := b.log2 if eb + 1024 < ea then Float.inf else let eb' := if b <<< ea ≤ a <<< eb then eb else eb + 1 let mantissa : UInt64 := (a <<< (eb' + 53) / b <<< ea).toUInt64 let rounded := if mantissa &&& 3 == 1 && a <<< (eb' + 53) == mantissa.toNat * (b <<< ea) then mantissa >>> 1 else (mantissa + 1) >>> 1 rounded.toFloat.scaleB (ea - (eb' + 52)) /-- Divide two integers, to produce a correctly rounded (nearest-ties-to-even) `Float` result. -/ protected def Int.divFloat (a b : Int) : Float := if (a ≥ 0) == (b ≥ 0) then a.natAbs.divFloat b.natAbs else -a.natAbs.divFloat b.natAbs
.lake/packages/batteries/Batteries/Lean/Json.lean
/- Copyright (c) 2022 E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: E.W.Ayers, Mario Carneiro -/ module public import Batteries.Lean.Float public import Lean.Data.Json.FromToJson.Basic @[expose] public section open Lean instance : OfScientific JsonNumber where ofScientific mantissa exponentSign decimalExponent := if exponentSign then { mantissa := mantissa, exponent := decimalExponent } else { mantissa := (mantissa * 10 ^ decimalExponent : Nat), exponent := 0 } instance : Neg JsonNumber where neg jn := ⟨-jn.mantissa, jn.exponent⟩ instance : ToJson Float where toJson x := match x.toRatParts' with | none => Json.null | some (n, d) => if d < 0 then Json.num { mantissa := n * (5^d.natAbs : Nat), exponent := d.natAbs } else Json.num { mantissa := n * (2^d.natAbs : Nat), exponent := 0 }
.lake/packages/batteries/Batteries/Lean/HashMap.lean
module public import Std.Data.HashMap.Basic @[expose] public section namespace Std.HashMap variable [BEq α] [Hashable α] /-- `O(|other|)` amortized. Merge two `HashMap`s. The values of keys which appear in both maps are combined using the monadic function `f`. -/ @[specialize] def mergeWithM {m α β} [BEq α] [Hashable α] [Monad m] (f : α → β → β → m β) (self other : HashMap α β) : m (HashMap α β) := other.foldM (init := self) fun map k v₂ => match map[k]? with | none => return map.insert k v₂ | some v₁ => return map.insert k (← f k v₁ v₂) /-- `O(|other|)` amortized. Merge two `HashMap`s. The values of keys which appear in both maps are combined using `f`. -/ @[inline] def mergeWith (f : α → β → β → β) (self other : HashMap α β) : HashMap α β := -- Implementing this function directly, rather than via `mergeWithM`, gives -- us less constrained universes. other.fold (init := self) fun map k v₂ => match map[k]? with | none => map.insert k v₂ | some v₁ => map.insert k <| f k v₁ v₂
.lake/packages/batteries/Batteries/Lean/Except.lean
module public import Lean.Util.Trace @[expose] public section open Lean namespace Except /-- Visualize an `Except` using a checkmark or a cross. -/ def emoji : Except ε α → String | .error _ => crossEmoji | .ok _ => checkEmoji @[simp] theorem map_error {ε : Type u} (f : α → β) (e : ε) : f <$> (.error e : Except ε α) = .error e := rfl @[simp] theorem map_ok {ε : Type u} (f : α → β) (x : α) : f <$> (.ok x : Except ε α) = .ok (f x) := rfl /-- Map a function over an `Except` value, using a proof that the value is `.ok`. -/ def pmap {ε : Type u} {α β : Type v} (x : Except ε α) (f : (a : α) → x = .ok a → β) : Except ε β := match x with | .error e => .error e | .ok a => .ok (f a rfl) @[simp] theorem pmap_error {ε : Type u} {α β : Type v} (e : ε) (f : (a : α) → Except.error e = Except.ok a → β) : Except.pmap (.error e) f = .error e := rfl @[simp] theorem pmap_ok {ε : Type u} {α β : Type v} (a : α) (f : (a' : α) → (.ok a : Except ε α) = .ok a' → β) : Except.pmap (.ok a) f = .ok (f a rfl) := rfl @[simp] theorem pmap_id {ε : Type u} {α : Type v} (x : Except ε α) : x.pmap (fun a _ => a) = x := by cases x <;> simp @[simp] theorem map_pmap (g : β → γ) (x : Except ε α) (f : (a : α) → x = .ok a → β) : g <$> x.pmap f = x.pmap fun a h => g (f a h) := by cases x <;> simp end Except namespace ExceptT -- This will be redundant after nightly-2024-11-08. attribute [ext] ExceptT.ext @[simp] theorem run_mk {m : Type u → Type v} (x : m (Except ε α)) : (ExceptT.mk x).run = x := rfl @[simp] theorem mk_run (x : ExceptT ε m α) : ExceptT.mk (ExceptT.run x) = x := rfl @[simp] theorem map_mk [Monad m] [LawfulMonad m] (f : α → β) (x : m (Except ε α)) : f <$> ExceptT.mk x = ExceptT.mk ((f <$> · ) <$> x) := by simp only [Functor.map, Except.map, ExceptT.map, map_eq_pure_bind] congr funext a split <;> simp end ExceptT
.lake/packages/batteries/Batteries/Lean/PersistentHashSet.lean
module public import Lean.Data.PersistentHashSet @[expose] public section namespace Lean.PersistentHashSet variable [BEq α] [Hashable α] instance : ForIn m (PersistentHashSet α) α where forIn s init step := do let mut state := init for (k, _) in s.set do match ← step k state with | .done state' => return state' | .yield state' => state := state' return state /-- Returns `true` if `f` returns `true` for any element of the set. -/ @[specialize] def anyM [Monad m] (s : PersistentHashSet α) (f : α → m Bool) : m Bool := do for a in s do if ← f a then return true return false /-- Returns `true` if `f` returns `true` for any element of the set. -/ @[inline] def any (s : PersistentHashSet α) (f : α → Bool) : Bool := Id.run <| s.anyM f /-- Returns `true` if `f` returns `true` for all elements of the set. -/ @[specialize] def allM [Monad m] (s : PersistentHashSet α) (f : α → m Bool) : m Bool := do for a in s do if ! (← f a) then return false return true /-- Returns `true` if `f` returns `true` for all elements of the set. -/ @[inline] def all (s : PersistentHashSet α) (f : α → Bool) : Bool := Id.run <| s.allM f instance : BEq (PersistentHashSet α) where beq s t := s.all (t.contains ·) && t.all (s.contains ·) /-- Insert all elements from a collection into a `PersistentHashSet`. -/ def insertMany [ForIn Id ρ α] (s : PersistentHashSet α) (as : ρ) : PersistentHashSet α := Id.run do let mut s := s for a in as do s := s.insert a return s /-- Obtain a `PersistentHashSet` from an array. -/ @[inline] protected def ofArray [BEq α] [Hashable α] (as : Array α) : PersistentHashSet α := PersistentHashSet.empty.insertMany as /-- Obtain a `PersistentHashSet` from a list. -/ @[inline] protected def ofList [BEq α] [Hashable α] (as : List α) : PersistentHashSet α := PersistentHashSet.empty.insertMany as /-- Merge two `PersistentHashSet`s. -/ @[inline] def merge (s t : PersistentHashSet α) : PersistentHashSet α := s.insertMany t
.lake/packages/batteries/Batteries/Lean/TagAttribute.lean
module public import Lean.Attributes @[expose] public section /-- Get the list of declarations tagged with the tag attribute `attr`. -/ def Lean.TagAttribute.getDecls (attr : TagAttribute) (env : Environment) : Array Name := core <| attr.ext.toEnvExtension.getState env where /-- Implementation of `TagAttribute.getDecls`. -/ core (st : PersistentEnvExtensionState Name NameSet) : Array Name := Id.run do let mut decls := st.state.toArray for ds in st.importedEntries do decls := decls ++ ds decls
.lake/packages/batteries/Batteries/Lean/EStateM.lean
module import all Init.Control.EState @[expose] public section namespace EStateM open Backtrackable namespace Result /-- Map a function over an `EStateM.Result`, preserving states and errors. -/ def map {ε σ α β} (f : α → β) (x : Result ε σ α) : Result ε σ β := match x with | .ok a s' => .ok (f a) s' | .error e s' => .error e s' @[simp] theorem map_ok {ε σ α β} (f : α → β) (a : α) (s : σ) : (Result.ok a s : Result ε σ α).map f = .ok (f a) s := rfl @[simp] theorem map_error {ε σ α β} (f : α → β) (e : ε) (s : σ) : (Result.error e s : Result ε σ α).map f = .error e s := rfl @[simp] theorem map_eq_ok {ε σ α β} {f : α → β} {x : Result ε σ α} {b : β} {s : σ} : x.map f = .ok b s ↔ ∃ a, x = .ok a s ∧ b = f a := by cases x <;> simp [and_assoc, and_comm, eq_comm] @[simp] theorem map_eq_error {ε σ α β} (f : α → β) {x : Result ε σ α} {e : ε} {s : σ} : x.map f = .error e s ↔ x = .error e s := by cases x <;> simp [eq_comm] end Result @[simp] theorem dummySave_apply (s : σ) : EStateM.dummySave s = PUnit.unit := rfl @[simp] theorem dummyRestore_apply (s : σ) : EStateM.dummyRestore s = Function.const _ s := rfl @[simp] theorem run_pure (x : α) (s : σ) : (pure x : EStateM ε σ α).run s = Result.ok x s := rfl @[simp] theorem run'_pure (x : α) (s : σ) : (pure x : EStateM ε σ α).run' s = some x := rfl @[simp] theorem run_bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) (s : σ) : (x >>= f).run s = match x.run s with | .ok a s => (f a).run s | .error e s => .error e s := rfl @[simp] theorem run'_bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) (s : σ) : (x >>= f).run' s = match x.run s with | .ok a s => (f a).run' s | .error _ _ => none := by rw [run', run_bind] cases x.run s <;> rfl @[simp] theorem run_map (f : α → β) (x : EStateM ε σ α) (s : σ) : (f <$> x).run s = (x.run s).map f := rfl @[simp] theorem run'_map (f : α → β) (x : EStateM ε σ α) (s : σ) : (f <$> x).run' s = Option.map f (x.run' s) := by rw [run', run', run_map] cases x.run s <;> rfl theorem run_seq (f : EStateM ε σ (α → β)) (x : EStateM ε σ α) (s : σ) : (f <*> x).run s = match f.run s with | .ok g s => Result.map g (x.run s) | .error e s => .error e s := by simp only [seq_eq_bind, run_bind, run_map] cases f.run s <;> rfl theorem run'_seq (f : EStateM ε σ (α → β)) (x : EStateM ε σ α) (s : σ) : (f <*> x).run' s = match f.run s with | .ok g s => Option.map g (x.run' s) | .error _ _ => none := by simp only [seq_eq_bind, run'_bind, run'_map] cases f.run s <;> rfl @[simp] theorem run_seqLeft (x : EStateM ε σ α) (y : EStateM ε σ β) (s : σ) : (x <* y).run s = match x.run s with | .ok v s => Result.map (fun _ => v) (y.run s) | .error e s => .error e s := by simp [seqLeft_eq_bind] @[simp] theorem run'_seqLeft (x : EStateM ε σ α) (y : EStateM ε σ β) (s : σ) : (x <* y).run' s = match x.run s with | .ok v s => Option.map (fun _ => v) (y.run' s) | .error _ _ => none := by simp [seqLeft_eq_bind] @[simp] theorem run_seqRight (x : EStateM ε σ α) (y : EStateM ε σ β) (s : σ) : (x *> y).run s = match x.run s with | .ok _ s => y.run s | .error e s => .error e s := rfl @[simp] theorem run'_seqRight (x : EStateM ε σ α) (y : EStateM ε σ β) (s : σ) : (x *> y).run' s = match x.run s with | .ok _ s => y.run' s | .error _ _ => none := by rw [run', run_seqRight] cases x.run s <;> rfl @[simp] theorem run_get (s : σ) : (get : EStateM ε σ σ).run s = Result.ok s s := rfl @[simp] theorem run'_get (s : σ) : (get : EStateM ε σ σ).run' s = some s := rfl @[simp] theorem run_set (v s : σ) : (set v : EStateM ε σ PUnit).run s = Result.ok PUnit.unit v := rfl @[simp] theorem run'_set (v s : σ) : (set v : EStateM ε σ PUnit).run' s = some PUnit.unit := rfl @[simp] theorem run_modify (f : σ → σ) (s : σ) : (modify f : EStateM ε σ PUnit).run s = Result.ok PUnit.unit (f s) := rfl @[simp] theorem run'_modify (f : σ → σ) (s : σ) : (modify f : EStateM ε σ PUnit).run' s = some PUnit.unit := rfl @[simp] theorem run_modifyGet (f : σ → α × σ) (s : σ) : (modifyGet f : EStateM ε σ α).run s = Result.ok (f s).1 (f s).2 := rfl @[simp] theorem run'_modifyGet (f : σ → α × σ) (s : σ) : (modifyGet f : EStateM ε σ α).run' s = some (f s).1 := rfl @[simp] theorem run_getModify (f : σ → σ) : (getModify f : EStateM ε σ σ).run s = Result.ok s (f s) := rfl @[simp] theorem run'_getModify (f : σ → σ) (s : σ) : (getModify f : EStateM ε σ σ).run' s = some s := rfl @[simp] theorem run_throw (e : ε) (s : σ) : (throw e : EStateM ε σ α).run s = Result.error e s := rfl @[simp] theorem run'_throw (e : ε) (s : σ) : (throw e : EStateM ε σ α).run' s = none := rfl @[simp] theorem run_orElse {δ} [h : Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) (s : σ) : (x₁ <|> x₂).run s = match x₁.run s with | .ok x s => .ok x s | .error _ s' => x₂.run (restore s' (save s)) := by show (EStateM.orElse _ _).run _ = _ unfold EStateM.orElse simp only [EStateM.run] match x₁ s with | .ok _ _ => rfl | .error _ _ => simp @[simp] theorem run'_orElse {δ} [h : Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) (s : σ) : (x₁ <|> x₂).run' s = match x₁.run s with | .ok x _ => some x | .error _ s' => x₂.run' (restore s' (save s)) := by rw [run', run_orElse] cases x₁.run s <;> rfl @[simp] theorem run_tryCatch {δ} [h : Backtrackable δ σ] (body : EStateM ε σ α) (handler : ε → EStateM ε σ α) (s : σ) : (tryCatch body handler).run s = match body.run s with | .ok x s => .ok x s | .error e s' => (handler e).run (restore s' (save s)) := by show (EStateM.tryCatch _ _).run _ = _ unfold EStateM.tryCatch simp only [EStateM.run] cases body s <;> rfl @[simp] theorem run'_tryCatch {δ} [h : Backtrackable δ σ] (body : EStateM ε σ α) (handler : ε → EStateM ε σ α) (s : σ) : (tryCatch body handler).run' s = match body.run s with | .ok x _ => some x | .error e s' => (handler e).run' (restore s' (save s)) := by rw [run', run_tryCatch] cases body.run s <;> rfl @[simp] theorem run_adaptExcept (f : ε → ε) (x : EStateM ε σ α) (s : σ) : (adaptExcept f x).run s = match x.run s with | .ok x s => .ok x s | .error e s => .error (f e) s := by show (EStateM.adaptExcept _ _).run _ = _ unfold EStateM.adaptExcept simp only [EStateM.run] cases x s <;> rfl @[simp] theorem run'_adaptExcept (f : ε → ε) (x : EStateM ε σ α) (s : σ) : (adaptExcept f x).run' s = x.run' s := by rw [run', run', run_adaptExcept] cases x.run s <;> rfl @[simp] theorem run_tryFinally' (x : EStateM ε σ α) (h : Option α → EStateM ε σ β) (s : σ) : (tryFinally' x h).run s = match x.run s with | .ok a s => match (h (some a)).run s with | .ok b s => Result.ok (a, b) s | .error e s => Result.error e s | .error e₁ s => match (h none).run s with | .ok _ s => Result.error e₁ s | .error e₂ s => Result.error e₂ s := rfl @[simp] theorem run'_tryFinally' (x : EStateM ε σ α) (h : Option α → EStateM ε σ β) (s : σ) : (tryFinally' x h).run' s = match x.run s with | .ok a s => Option.map (a, ·) ((h (some a)).run' s) | .error _ _ => none := by simp [run', run_tryFinally'] match x.run s with | .ok a s => simp only; cases (h (some a)).run s <;> rfl | .error e s => simp only; cases (h none).run s <;> rfl @[simp] theorem run_fromStateM (x : StateM σ α) (s : σ) : (fromStateM x : EStateM ε σ α).run s = Result.ok (x.run s).1 (x.run s).2 := (rfl) @[simp] theorem run'_fromStateM (x : StateM σ α) (s : σ) : (fromStateM x : EStateM ε σ α).run' s = some (x.run' s) := (rfl) @[ext] theorem ext {ε σ α} {x y : EStateM ε σ α} (h : ∀ s, x.run s = y.run s) : x = y := by funext s exact h s end EStateM
.lake/packages/batteries/Batteries/Lean/Syntax.lean
module public import Lean.Syntax @[expose] public section /-! # Helper functions for working with typed syntaxes. -/ namespace Lean /-- Applies the given function to every subsyntax. Like `Syntax.replaceM` but for typed syntax. (Note there are no guarantees of type correctness here.) -/ def TSyntax.replaceM [Monad M] (f : Syntax → M (Option Syntax)) (stx : TSyntax k) : M (TSyntax k) := .mk <$> stx.1.replaceM f
.lake/packages/batteries/Batteries/Lean/LawfulMonadLift.lean
module public import Lean.Elab.Command import all Lean.CoreM -- for unfolding `liftIOCore` import all Init.System.IO -- for unfolding `BaseIO.toEIO` import all Init.Control.StateRef -- for unfolding `StateRefT'.lift` @[expose] public section /-! # Lawful instances of `MonadLift` for the Lean monad stack. -/ open Lean Elab Term Tactic Command instance : LawfulMonadLift BaseIO (EIO ε) where monadLift_pure _ := rfl monadLift_bind ma f := by simp only [MonadLift.monadLift, bind] unfold BaseIO.toEIO EStateM.bind IO.RealWorld simp only funext x rcases ma x with a | a · simp only · contradiction instance : LawfulMonadLift (ST σ) (EST ε σ) where monadLift_pure a := rfl monadLift_bind ma f := by simp only [MonadLift.monadLift, bind] unfold EStateM.bind simp only funext x rcases ma x with a | a · simp only · contradiction instance : LawfulMonadLift IO CoreM where monadLift_pure _ := rfl monadLift_bind ma f := by simp only [MonadLift.monadLift, bind, pure, Core.liftIOCore, liftM, monadLift, getRef, read, readThe, MonadReaderOf.read, IO.toEIO] unfold StateRefT'.lift ReaderT.read ReaderT.bind ReaderT.pure simp only [Function.comp_apply, bind, pure] unfold ReaderT.bind ReaderT.pure simp only [bind, pure] unfold EStateM.adaptExcept EStateM.bind EStateM.pure simp only funext _ _ s rcases ma s with a | a <;> simp only instance : LawfulMonadLiftT (EIO Exception) CommandElabM := inferInstance instance : LawfulMonadLiftT (EIO Exception) CoreM := inferInstance instance : LawfulMonadLiftT CoreM MetaM := inferInstance instance : LawfulMonadLiftT MetaM TermElabM := inferInstance instance : LawfulMonadLiftT TermElabM TacticM := inferInstance
.lake/packages/batteries/Batteries/Lean/NameMapAttribute.lean
module public import Lean.Attributes @[expose] public section namespace Lean /-- Maps declaration names to `α`. -/ def NameMapExtension (α : Type) := SimplePersistentEnvExtension (Name × α) (NameMap α) instance : Inhabited (NameMapExtension α) := inferInstanceAs <| Inhabited (SimplePersistentEnvExtension ..) /-- Look up a value in the given extension in the environment. -/ def NameMapExtension.find? (ext : NameMapExtension α) (env : Environment) : Name → Option α := (SimplePersistentEnvExtension.getState ext env).find? /-- Add the given k,v pair to the NameMapExtension. -/ def NameMapExtension.add [Monad M] [MonadEnv M] [MonadError M] (ext : NameMapExtension α) (k : Name) (v : α) : M Unit := do if let some _ := ext.find? (← getEnv) k then throwError "Already exists entry for {ext.name} {k}" else ext.addEntry (← getEnv) (k, v) |> setEnv /-- Registers a new extension with the given name and type. -/ def registerNameMapExtension (α) (name : Name := by exact decl_name%) : IO (NameMapExtension α) := do registerSimplePersistentEnvExtension { name addImportedFn := fun ass => ass.foldl (init := ∅) fun names as => as.foldl (init := names) fun names (a, b) => names.insert a b addEntryFn := fun s n => s.insert n.1 n.2 toArrayFn := fun es => es.toArray } /-- The inputs to `registerNameMapAttribute`. -/ structure NameMapAttributeImpl (α : Type) where /-- The name of the attribute -/ name : Name /-- The declaration which creates the attribute -/ ref : Name := by exact decl_name% /-- The description of the attribute -/ descr : String /-- This function is called when the attribute is applied. It should produce a value of type `α` from the given attribute syntax. -/ add (src : Name) (stx : Syntax) : AttrM α deriving Inhabited /-- Similar to `registerParametricAttribute` except that attributes do not have to be assigned in the same file as the declaration. -/ def registerNameMapAttribute (impl : NameMapAttributeImpl α) : IO (NameMapExtension α) := do let ext ← registerNameMapExtension α impl.ref registerBuiltinAttribute { name := impl.name descr := impl.descr add := fun src stx _kind => do let a : α ← impl.add src stx ext.add src a } return ext
.lake/packages/batteries/Batteries/Lean/SatisfiesM.lean
module public import Batteries.Classes.SatisfiesM public import Batteries.Lean.LawfulMonad public import Lean.Elab.Command @[expose] public section /-! # Construct `MonadSatisfying` instances for the Lean monad stack. -/ open Lean Elab Term Tactic Command instance : MonadSatisfying (EIO ε) := inferInstanceAs <| MonadSatisfying (EStateM _ _) instance : MonadSatisfying BaseIO := inferInstanceAs <| MonadSatisfying (EIO _) instance : MonadSatisfying IO := inferInstanceAs <| MonadSatisfying (EIO _) instance : MonadSatisfying (EST ε σ) := inferInstanceAs <| MonadSatisfying (EStateM _ _) instance : MonadSatisfying CoreM := inferInstanceAs <| MonadSatisfying (ReaderT _ <| StateRefT' _ _ (EIO _)) instance : MonadSatisfying MetaM := inferInstanceAs <| MonadSatisfying (ReaderT _ <| StateRefT' _ _ CoreM) instance : MonadSatisfying TermElabM := inferInstanceAs <| MonadSatisfying (ReaderT _ <| StateRefT' _ _ MetaM) instance : MonadSatisfying TacticM := inferInstanceAs <| MonadSatisfying (ReaderT _ $ StateRefT' _ _ TermElabM) instance : MonadSatisfying CommandElabM := inferInstanceAs <| MonadSatisfying (ReaderT _ $ StateRefT' _ _ (EIO _))
.lake/packages/batteries/Batteries/Lean/PersistentHashMap.lean
module public import Lean.Data.PersistentHashMap @[expose] public section namespace Lean.PersistentHashMap variable [BEq α] [Hashable α] /-- Builds a `PersistentHashMap` from a list of key-value pairs. Values of duplicated keys are replaced by their respective last occurrences. -/ def ofList (xs : List (α × β)) : PersistentHashMap α β := xs.foldl (init := {}) fun m (k, v) => m.insert k v /-- Variant of `ofList` which accepts a function that combines values of duplicated keys. -/ def ofListWith (xs : List (α × β)) (f : α → β → β → β) : PersistentHashMap α β := xs.foldl (init := {}) fun m (k, v) => match m.find? k with | none => m.insert k v | some v' => m.insert k <| f k v v' /-- Builds a `PersistentHashMap` from an array of key-value pairs. Values of duplicated keys are replaced by their respective last occurrences. -/ def ofArray (xs : Array (α × β)) : PersistentHashMap α β := xs.foldl (init := {}) fun m (k, v) => m.insert k v /-- Variant of `ofArray` which accepts a function that combines values of duplicated keys. -/ def ofArrayWith (xs : Array (α × β)) (f : α → β → β → β) : PersistentHashMap α β := xs.foldl (init := {}) fun m (k, v) => match m.find? k with | none => m.insert k v | some v' => m.insert k <| f k v v' /-- Merge two `PersistentHashMap`s. The values of keys which appear in both maps are combined using the monadic function `f`. -/ @[specialize] def mergeWithM [Monad m] (self other : PersistentHashMap α β) (f : α → β → β → m β) : m (PersistentHashMap α β) := other.foldlM (init := self) fun map k v₂ => match map.find? k with | none => return map.insert k v₂ | some v₁ => return map.insert k (← f k v₁ v₂) /-- Merge two `PersistentHashMap`s. The values of keys which appear in both maps are combined using `f`. -/ @[inline] def mergeWith (self other : PersistentHashMap α β) (f : α → β → β → β) : PersistentHashMap α β := -- Implementing this function directly, rather than via `mergeWithM`, gives -- us less constrained universes. other.foldl (init := self) fun map k v₂ => match map.find? k with | none => map.insert k v₂ | some v₁ => map.insert k <| f k v₁ v₂
.lake/packages/batteries/Batteries/Lean/MonadBacktrack.lean
module public import Lean.Util.MonadBacktrack @[expose] public section namespace Lean /-- Execute the action `x`, then restore the initial state. Returns the state after `x` finished. -/ def withoutModifyingState' [Monad m] [MonadBacktrack s m] [MonadFinally m] (x : m α) : m (α × s) := withoutModifyingState do let result ← x let finalState ← saveState return (result, finalState) end Lean
.lake/packages/batteries/Batteries/Lean/HashSet.lean
module public import Std.Data.HashSet.Basic @[expose] public section namespace Std.HashSet variable [BEq α] [Hashable α] /-- `O(n)`. Returns `true` if `f` returns `true` for any element of the set. -/ @[specialize] def anyM [Monad m] (s : HashSet α) (f : α → m Bool) : m Bool := do for a in s do if ← f a then return true return false /-- `O(n)`. Returns `true` if `f` returns `true` for all elements of the set. -/ @[specialize] def allM [Monad m] (s : HashSet α) (f : α → m Bool) : m Bool := do for a in s do if !(← f a) then return false return true instance : BEq (HashSet α) where beq s t := s.all (t.contains ·) && t.all (s.contains ·)
.lake/packages/batteries/Batteries/Lean/Expr.lean
module public import Lean.Elab.Term public import Lean.Elab.Binders @[expose] public section /-! # Additional operations on Expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. -/ namespace Lean.Expr open Lean.Elab.Term in /-- Converts an `Expr` into a `Syntax`, by creating a fresh metavariable assigned to the expr and returning a named metavariable syntax `?a`. -/ def toSyntax (e : Expr) : TermElabM Syntax.Term := withFreshMacroScope do let stx ← `(?a) let mvar ← elabTermEnsuringType stx (← Meta.inferType e) mvar.mvarId!.assign e pure stx /-- Like `withApp` but ignores metadata. -/ @[inline] def withApp' (e : Expr) (k : Expr → Array Expr → α) : α := let dummy := mkSort levelZero let nargs := e.getAppNumArgs' go e (.replicate nargs dummy) (nargs - 1) where /-- Auxiliary definition for `withApp'`. -/ @[specialize] go : Expr → Array Expr → Nat → α | mdata _ b, as, i => go b as i | app f a , as, i => go f (as.set! i a) (i-1) | f , as, _ => k f as /-- Like `getAppArgs` but ignores metadata. -/ @[inline] def getAppArgs' (e : Expr) : Array Expr := e.withApp' λ _ as => as /-- Like `traverseApp` but ignores metadata. -/ def traverseApp' {m} [Monad m] (f : Expr → m Expr) (e : Expr) : m Expr := e.withApp' λ fn args => return mkAppN (← f fn) (← args.mapM f) /-- Like `withAppRev` but ignores metadata. -/ @[inline] def withAppRev' (e : Expr) (k : Expr → Array Expr → α) : α := go e (Array.mkEmpty e.getAppNumArgs') where /-- Auxiliary definition for `withAppRev'`. -/ @[specialize] go : Expr → Array Expr → α | mdata _ b, as => go b as | app f a , as => go f (as.push a) | f , as => k f as /-- Like `getAppRevArgs` but ignores metadata. -/ @[inline] def getAppRevArgs' (e : Expr) : Array Expr := e.withAppRev' λ _ as => as /-- Like `getRevArgD` but ignores metadata. -/ def getRevArgD' : Expr → Nat → Expr → Expr | mdata _ b, n , v => getRevArgD' b n v | app _ a , 0 , _ => a | app f _ , i+1, v => getRevArgD' f i v | _ , _ , v => v /-- Like `getArgD` but ignores metadata. -/ @[inline] def getArgD' (e : Expr) (i : Nat) (v₀ : Expr) (n := e.getAppNumArgs') : Expr := getRevArgD' e (n - i - 1) v₀ /-- Like `isAppOf` but ignores metadata. -/ def isAppOf' (e : Expr) (n : Name) : Bool := match e.getAppFn' with | const c .. => c == n | _ => false /-- Turns an expression that is a natural number literal into a natural number. -/ def natLit! : Expr → Nat | lit (Literal.natVal v) => v | _ => panic! "nat literal expected" /-- Turns an expression that is a constructor of `Int` applied to a natural number literal into an integer. -/ def intLit! (e : Expr) : Int := if e.isAppOfArity ``Int.ofNat 1 then e.appArg!.natLit! else if e.isAppOfArity ``Int.negOfNat 1 then .negOfNat e.appArg!.natLit! else panic! "not a raw integer literal" open Lean Elab Term in /-- Annotates a `binderIdent` with the binder information from an `fvar`. -/ def addLocalVarInfoForBinderIdent (fvar : Expr) (tk : TSyntax ``binderIdent) : MetaM Unit := -- the only TermElabM thing we do in `addLocalVarInfo` is check inPattern, -- which we assume is always false for this function discard <| TermElabM.run do match tk with | `(binderIdent| $n:ident) => Elab.Term.addLocalVarInfo n fvar | tk => Elab.Term.addLocalVarInfo (Unhygienic.run `(_%$tk)) fvar
.lake/packages/batteries/Batteries/Lean/AttributeExtra.lean
module public import Batteries.Lean.TagAttribute public import Std.Data.HashMap.Basic @[expose] public section open Lean namespace Lean open Std /-- `TagAttributeExtra` works around a limitation of `TagAttribute`, which is that definitions must be tagged in the same file that declares the definition. This works well for definitions in lean core, but for attributes declared outside the core this is problematic because we may want to tag declarations created before the attribute was defined. To resolve this, we allow a one-time exception to the rule that attributes must be applied in the same file as the declaration: During the declaration of the attribute itself, we can tag arbitrary other definitions, but once the attribute is declared we must tag things in the same file as normal. -/ structure TagAttributeExtra where /-- The environment extension for the attribute. -/ ext : PersistentEnvExtension Name Name NameSet /-- A list of "base" declarations which have been pre-tagged. -/ base : NameHashSet deriving Inhabited /-- Registers a new tag attribute. The `extra` field is a list of definitions from other modules which will be "pre-tagged" and are not subject to the usual restriction on tagging in the same file as the declaration. Note: The `extra` fields bypass the `validate` function - we assume the builtins are also pre-validated. -/ def registerTagAttributeExtra (name : Name) (descr : String) (extra : List Name) (validate : Name → AttrM Unit := fun _ => pure ()) (ref : Name := by exact decl_name%) : IO TagAttributeExtra := do let { ext, .. } ← registerTagAttribute name descr validate ref pure { ext, base := extra.foldl (·.insert ·) {} } namespace TagAttributeExtra /-- Does declaration `decl` have the tag `attr`? -/ def hasTag (attr : TagAttributeExtra) (env : Environment) (decl : Name) : Bool := match env.getModuleIdxFor? decl with | some modIdx => (attr.ext.getModuleEntries env modIdx).binSearchContains decl Name.quickLt | none => (attr.ext.getState env).contains decl || attr.base.contains decl /-- Get the list of declarations tagged with the tag attribute `attr`. -/ def getDecls (attr : TagAttributeExtra) (env : Environment) : Array Name := Id.run do let decls := TagAttribute.getDecls.core <| attr.ext.toEnvExtension.getState env attr.base.fold (·.push ·) decls end TagAttributeExtra /-- `ParametricAttributeExtra` works around a limitation of `ParametricAttribute`, which is that definitions must be tagged in the same file that declares the definition. This works well for definitions in lean core, but for attributes declared outside the core this is problematic because we may want to tag declarations created before the attribute was defined. To resolve this, we allow a one-time exception to the rule that attributes must be applied in the same file as the declaration: During the declaration of the attribute itself, we can tag arbitrary other definitions, but once the attribute is declared we must tag things in the same file as normal. -/ structure ParametricAttributeExtra (α : Type) where /-- The underlying `ParametricAttribute`. -/ attr : ParametricAttribute α /-- A list of pre-tagged declarations with their values. -/ base : Std.HashMap Name α deriving Inhabited /-- Registers a new parametric attribute. The `extra` field is a list of definitions from other modules which will be "pre-tagged" and are not subject to the usual restriction on tagging in the same file as the declaration. -/ def registerParametricAttributeExtra (impl : ParametricAttributeImpl α) (extra : List (Name × α)) : IO (ParametricAttributeExtra α) := do let attr ← registerParametricAttribute impl pure { attr, base := extra.foldl (fun s (a, b) => s.insert a b) {} } namespace ParametricAttributeExtra /-- Gets the parameter of attribute `attr` associated to declaration `decl`, or `none` if `decl` is not tagged. -/ def getParam? [Inhabited α] (attr : ParametricAttributeExtra α) (env : Environment) (decl : Name) : Option α := attr.attr.getParam? env decl <|> attr.base[decl]? /-- Applies attribute `attr` to declaration `decl`, given a value for the parameter. -/ def setParam (attr : ParametricAttributeExtra α) (env : Environment) (decl : Name) (param : α) : Except String Environment := attr.attr.setParam env decl param end ParametricAttributeExtra
.lake/packages/batteries/Batteries/Lean/Position.lean
module public import Lean.Syntax public import Lean.Data.Lsp.Utf16 @[expose] public section /-- Gets the LSP range of syntax `stx`. -/ @[deprecated Lean.FileMap.lspRangeOfStx? (since := "2025-09-23")] def Lean.FileMap.rangeOfStx? (text : FileMap) (stx : Syntax) : Option Lsp.Range := text.utf8RangeToLspRange <$> stx.getRange? /-- Return the beginning of the line contatining character `pos`. -/ def Lean.findLineStart (s : String) (pos : String.Pos.Raw) : String.Pos.Raw := match s.revFindAux (· = '\n') pos with | none => 0 | some n => ⟨n.byteIdx + 1⟩ /-- Return the indentation (number of leading spaces) of the line containing `pos`, and whether `pos` is the first non-whitespace character in the line. -/ def Lean.findIndentAndIsStart (s : String) (pos : String.Pos.Raw) : Nat × Bool := let start := findLineStart s pos let body := s.findAux (· ≠ ' ') pos start (start.byteDistance body, body == pos)
.lake/packages/batteries/Batteries/Lean/Util/EnvSearch.lean
module public import Batteries.Tactic.Lint.Misc namespace Lean /-- Find constants in current environment that match find options and predicate. -/ public meta def getMatchingConstants {m} [Monad m] [MonadEnv m] (p : ConstantInfo → m Bool) (includeImports := true) : m (Array ConstantInfo) := do let matches_ ← if includeImports then (← getEnv).constants.map₁.foldM (init := #[]) check else pure #[] (← getEnv).constants.map₂.foldlM (init := matches_) check where /-- Check constant should be returned -/ @[nolint unusedArguments] check matches_ (_name : Name) cinfo := do if ← p cinfo then pure $ matches_.push cinfo else pure matches_
.lake/packages/batteries/Batteries/Lean/IO/Process.lean
module @[expose] public section /-! # Running external commands. -/ namespace IO.Process open System (FilePath) /-- Pipe `input` into stdin of the spawned process, then return `(exitCode, stdout, stdErr)` upon completion. -/ def runCmdWithInput' (cmd : String) (args : Array String) (input : String := "") (throwFailure := true) : IO Output := do let child ← spawn { cmd := cmd, args := args, stdin := .piped, stdout := .piped, stderr := .piped } let (stdin, child) ← child.takeStdin stdin.putStr input stdin.flush let stdout ← IO.asTask child.stdout.readToEnd Task.Priority.dedicated let err ← child.stderr.readToEnd let exitCode ← child.wait if exitCode != 0 && throwFailure then throw $ IO.userError err else let out ← IO.ofExcept stdout.get return ⟨exitCode, out, err⟩ /-- Pipe `input` into stdin of the spawned process, then return the entire content of stdout as a `String` upon completion. -/ def runCmdWithInput (cmd : String) (args : Array String) (input : String := "") (throwFailure := true) : IO String := do return (← runCmdWithInput' cmd args input throwFailure).stdout
.lake/packages/batteries/Batteries/Lean/Meta/InstantiateMVars.lean
module public import Batteries.Lean.Meta.Basic @[expose] public section open Lean Lean.Meta namespace Lean.MVarId /-- Instantiate metavariables in the type of the given metavariable, update the metavariable's declaration and return the new type. -/ def instantiateMVarsInType [Monad m] [MonadMCtx m] [MonadError m] (mvarId : MVarId) : m Expr := do let mdecl ← (← getMCtx).getExprMVarDecl mvarId let type := mdecl.type if type.hasMVar then let type ← instantiateMVars type let mdecl := { mdecl with type } modifyMCtx (·.declareExprMVar mvarId mdecl) return type else return type /-- Instantiate metavariables in the `LocalDecl` of the given fvar, update the `LocalDecl` and return the new `LocalDecl.` -/ def instantiateMVarsInLocalDecl [Monad m] [MonadMCtx m] [MonadError m] (mvarId : MVarId) (fvarId : FVarId) : m LocalDecl := do let mdecl ← (← getMCtx).getExprMVarDecl mvarId let (some ldecl) := mdecl.lctx.find? fvarId | throwError "unknown fvar '{fvarId.name}' (in local context of mvar '?{mvarId.name}')" let ldecl ← Lean.instantiateLocalDeclMVars ldecl let mdecl := { mdecl with lctx := mdecl.lctx.modifyLocalDecl fvarId fun _ => ldecl } modifyMCtx (·.declareExprMVar mvarId mdecl) return ldecl /-- Instantiate metavariables in the local context of the given metavariable, update the metavariable's declaration and return the new local context. -/ def instantiateMVarsInLocalContext [Monad m] [MonadMCtx m] [MonadError m] (mvarId : MVarId) : m LocalContext := do let mdecl ← (← getMCtx).getExprMVarDecl mvarId let lctx ← instantiateLCtxMVars mdecl.lctx modifyMCtx (·.declareExprMVar mvarId { mdecl with lctx }) return lctx /-- Instantiate metavariables in the local context and type of the given metavariable. -/ def instantiateMVars [Monad m] [MonadMCtx m] [MonadError m] (mvarId : MVarId) : m Unit := do discard $ (← getMCtx).getExprMVarDecl mvarId -- The line above throws an error if the `mvarId` is not declared. The line -- below panics. instantiateMVarDeclMVars mvarId end Lean.MVarId
.lake/packages/batteries/Batteries/Lean/Meta/SavedState.lean
module public import Batteries.Lean.Meta.Basic public import Batteries.Lean.MonadBacktrack @[expose] public section namespace Lean.Meta.SavedState /-- Run the action `x` in state `s`. Returns the result of `x` and the state after `x` was executed. The global state remains unchanged. -/ def runMetaM (s : Meta.SavedState) (x : MetaM α) : MetaM (α × Meta.SavedState) := withoutModifyingState' do restoreState s; x /-- Run the action `x` in state `s`. Returns the result of `x`. The global state remains unchanged. -/ def runMetaM' (s : Meta.SavedState) (x : MetaM α) : MetaM α := withoutModifyingState do restoreState s; x end SavedState /-- Returns the mvars that are not declared in `preState`, but declared and unassigned in `postState`. Delayed-assigned mvars are considered assigned. -/ def getIntroducedExprMVars (preState postState : SavedState) : MetaM (Array MVarId) := do let unassignedPost ← postState.runMetaM' getUnassignedExprMVars preState.runMetaM' do unassignedPost.filterM fun mvarId => return ! (← mvarId.isDeclared) /-- Returns the mvars that are declared but unassigned in `preState`, and assigned in `postState`. Delayed-assigned mvars are considered assigned. -/ def getAssignedExprMVars (preState postState : SavedState) : MetaM (Array MVarId) := do let unassignedPre ← preState.runMetaM' getUnassignedExprMVars postState.runMetaM' do unassignedPre.filterM (·.isAssignedOrDelayedAssigned) end Lean.Meta
.lake/packages/batteries/Batteries/Lean/Meta/Basic.lean
module public import Lean.Meta.Tactic.Intro public import Batteries.Control.AlternativeMonad import Lean.Meta.SynthInstance public section open Lean Lean.Meta namespace Lean /-- Sort the given `FVarId`s by the order in which they appear in the current local context. If any of the `FVarId`s do not appear in the current local context, the result is unspecified. -/ def Meta.sortFVarsByContextOrder [Monad m] [MonadLCtx m] (hyps : Array FVarId) : m (Array FVarId) := return (← getLCtx).sortFVarsByContextOrder hyps instance : AlternativeMonad Lean.Meta.MetaM where namespace MetavarContext /-- Get the `MetavarDecl` of `mvarId`. If `mvarId` is not a declared metavariable in the given `MetavarContext`, throw an error. -/ def getExprMVarDecl [Monad m] [MonadError m] (mctx : MetavarContext) (mvarId : MVarId) : m MetavarDecl := do if let some mdecl := mctx.decls.find? mvarId then return mdecl else throwError "unknown metavariable '?{mvarId.name}'" /-- Declare a metavariable. You must make sure that the metavariable is not already declared. -/ def declareExprMVar (mctx : MetavarContext) (mvarId : MVarId) (mdecl : MetavarDecl) : MetavarContext := { mctx with decls := mctx.decls.insert mvarId mdecl } /-- Check whether a metavariable is assigned or delayed-assigned. A delayed-assigned metavariable is already 'solved' but the solution cannot be substituted yet because we have to wait for some other metavariables to be assigned first. So in most situations you want to treat a delayed-assigned metavariable as assigned. -/ def isExprMVarAssignedOrDelayedAssigned (mctx : MetavarContext) (mvarId : MVarId) : Bool := mctx.eAssignment.contains mvarId || mctx.dAssignment.contains mvarId /-- Check whether a metavariable is declared in the given `MetavarContext`. -/ def isExprMVarDeclared (mctx : MetavarContext) (mvarId : MVarId) : Bool := mctx.decls.contains mvarId /-- Erase any assignment or delayed assignment of the given metavariable. -/ def eraseExprMVarAssignment (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := { mctx with eAssignment := mctx.eAssignment.erase mvarId dAssignment := mctx.dAssignment.erase mvarId } /-- Obtain all unassigned metavariables from the given `MetavarContext`. If `includeDelayed` is `true`, delayed-assigned metavariables are considered unassigned. -/ def unassignedExprMVars (mctx : MetavarContext) (includeDelayed := false) : Array MVarId := Id.run do let mut result := #[] for (mvarId, _) in mctx.decls do if ! mctx.eAssignment.contains mvarId && (includeDelayed || ! mctx.dAssignment.contains mvarId) then result := result.push mvarId return result end MetavarContext namespace MVarId /-- Check whether a metavariable is declared. -/ def isDeclared [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := return (← getMCtx).isExprMVarDeclared mvarId /-- Erase any assignment or delayed assignment of the given metavariable. -/ def eraseAssignment [MonadMCtx m] (mvarId : MVarId) : m Unit := modifyMCtx (·.eraseExprMVarAssignment mvarId) /-- Solve a goal by synthesizing an instance. -/ -- FIXME: probably can just be `g.inferInstance` once leanprover/lean4#2054 is fixed def synthInstance (g : MVarId) : MetaM Unit := do g.assign (← Lean.Meta.synthInstance (← g.getType)) /-- Get the type the given metavariable after instantiating metavariables and cleaning up annotations. -/ def getTypeCleanup (mvarId : MVarId) : MetaM Expr := return (← instantiateMVars (← mvarId.getType)).cleanupAnnotations end MVarId namespace Meta /-- Obtain all unassigned metavariables. If `includeDelayed` is `true`, delayed-assigned metavariables are considered unassigned. -/ def getUnassignedExprMVars [Monad m] [MonadMCtx m] (includeDelayed := false) : m (Array MVarId) := return (← getMCtx).unassignedExprMVars (includeDelayed := includeDelayed) /-- Run a computation with hygiene turned off. -/ def unhygienic [MonadWithOptions m] (x : m α) : m α := withOptions (tactic.hygienic.set · false) x /-- A variant of `mkFreshId` which generates names with a particular prefix. The generated names are unique and have the form `<prefix>.<N>` where `N` is a natural number. They are not suitable as user-facing names. -/ def mkFreshIdWithPrefix [Monad m] [MonadNameGenerator m] («prefix» : Name) : m Name := do let ngen ← getNGen let r := { ngen with namePrefix := «prefix» }.curr setNGen ngen.next pure r /-- `saturate1 goal tac` runs `tac` on `goal`, then on the resulting goals, etc., until `tac` does not apply to any goal any more (i.e. it returns `none`). The order of applications is depth-first, so if `tac` generates goals `[g₁, g₂, ⋯]`, we apply `tac` to `g₁` and recursively to all its subgoals before visiting `g₂`. If `tac` does not apply to `goal`, `saturate1` returns `none`. Otherwise it returns the generated subgoals to which `tac` did not apply. `saturate1` respects the `MonadRecDepth` recursion limit. -/ partial def saturate1 [Monad m] [MonadError m] [MonadRecDepth m] [MonadLiftT (ST IO.RealWorld) m] (goal : MVarId) (tac : MVarId → m (Option (Array MVarId))) : m (Option (Array MVarId)) := do let some goals ← tac goal | return none let acc ← ST.mkRef #[] goals.forM (go acc) return some (← acc.get) where /-- Auxiliary definition for `saturate1`. -/ go (acc : IO.Ref (Array MVarId)) (goal : MVarId) : m Unit := withIncRecDepth do match ← tac goal with | none => acc.modify fun s => s.push goal | some goals => goals.forM (go acc)
.lake/packages/batteries/Batteries/Lean/Meta/Simp.lean
module public import Lean.Elab.Tactic.Simp public import Batteries.Tactic.OpenPrivate import all Lean.Elab.Tactic.Simp -- for accessing `mkDischargeWrapper` public section /-! # Helper functions for using the simplifier. [TODO] Reunification of `mkSimpContext'` with core. -/ namespace Lean namespace Meta.Simp open Elab.Tactic /-- Flip the proof in a `Simp.Result`. -/ def mkEqSymm (e : Expr) (r : Simp.Result) : MetaM Simp.Result := ({ expr := e, proof? := · }) <$> match r.proof? with | none => pure none | some p => some <$> Meta.mkEqSymm p /-- Construct the `Expr` `cast h e`, from a `Simp.Result` with proof `h`. -/ def mkCast (r : Simp.Result) (e : Expr) : MetaM Expr := do mkAppM ``cast #[← r.getProof, e] /-- Construct a `Simp.DischargeWrapper` from the `Syntax` for a `simp` discharger. -/ nonrec def mkDischargeWrapper := mkDischargeWrapper -- copied from core /-- If `ctx == false`, the config argument is assumed to have type `Meta.Simp.Config`, and `Meta.Simp.ConfigCtx` otherwise. If `ctx == false`, the `discharge` option must be none -/ def mkSimpContext' (simpTheorems : SimpTheorems) (stx : Syntax) (eraseLocal : Bool) (kind := SimpKind.simp) (ctx := false) (ignoreStarArg : Bool := false) : TacticM MkSimpContextResult := do if ctx && !stx[2].isNone then if kind == SimpKind.simpAll then throwError "'simp_all' tactic does not support 'discharger' option" if kind == SimpKind.dsimp then throwError "'dsimp' tactic does not support 'discharger' option" let dischargeWrapper ← mkDischargeWrapper stx[2] let simpOnly := !stx[3].isNone let simpTheorems ← if simpOnly then simpOnlyBuiltins.foldlM (·.addConst ·) {} else pure simpTheorems let simprocs ← if simpOnly then pure {} else Simp.getSimprocs let congrTheorems ← Meta.getSimpCongrTheorems let ctx ← Simp.mkContext (← elabSimpConfig stx[1] (kind := kind)) #[simpTheorems] congrTheorems let r ← elabSimpArgs stx[4] (simprocs := #[simprocs]) ctx eraseLocal kind (ignoreStarArg := ignoreStarArg) return { r with dischargeWrapper } end Simp end Lean.Meta
.lake/packages/batteries/Batteries/Lean/Meta/Inaccessible.lean
module public import Lean.Meta.Basic @[expose] public section open Lean Lean.Meta Std /-- Obtain the inaccessible fvars from the given local context. An fvar is inaccessible if (a) its user name is inaccessible or (b) it is shadowed by a later fvar with the same user name. -/ def Lean.LocalContext.inaccessibleFVars (lctx : LocalContext) : Array LocalDecl := let (result, _) := lctx.foldr (β := Array LocalDecl × Std.HashSet Name) (init := (Array.mkEmpty lctx.numIndices, {})) fun ldecl (result, seen) => if ldecl.isImplementationDetail then (result, seen) else let result := if ldecl.userName.hasMacroScopes || seen.contains ldecl.userName then result.push ldecl else result (result, seen.insert ldecl.userName) result.reverse /-- Obtain the inaccessible fvars from the current local context. An fvar is inaccessible if (a) its user name is inaccessible or (b) it is shadowed by a later fvar with the same user name. -/ def Lean.Meta.getInaccessibleFVars [Monad m] [MonadLCtx m] : m (Array LocalDecl) := return (← getLCtx).inaccessibleFVars /-- Rename all inaccessible fvars. An fvar is inaccessible if (a) its user name is inaccessible or (b) it is shadowed by a later fvar with the same user name. This function gives all inaccessible fvars a unique, accessible user name. It returns the new goal and the fvars that were renamed. -/ def Lean.MVarId.renameInaccessibleFVars (mvarId : MVarId) : MetaM (MVarId × Array FVarId) := do let mdecl ← mvarId.getDecl let mut lctx := mdecl.lctx let inaccessibleFVars := lctx.inaccessibleFVars if inaccessibleFVars.isEmpty then return (mvarId, #[]) let mut renamedFVars := Array.mkEmpty lctx.decls.size for ldecl in inaccessibleFVars do let newName := lctx.getUnusedName ldecl.userName lctx := lctx.setUserName ldecl.fvarId newName renamedFVars := renamedFVars.push ldecl.fvarId let newMVar ← mkFreshExprMVarAt lctx mdecl.localInstances mdecl.type mvarId.assign newMVar return (newMVar.mvarId!, renamedFVars)
.lake/packages/batteries/Batteries/Lean/Meta/Expr.lean
module public import Lean.Expr @[expose] public section namespace Lean.Literal instance : Ord Literal where compare | natVal n₁, natVal n₂ => compare n₁ n₂ | strVal s₁, strVal s₂ => compare s₁ s₂ | natVal _, strVal _ => .lt | strVal _, natVal _ => .gt
.lake/packages/batteries/Batteries/Lean/Meta/UnusedNames.lean
module public import Lean.LocalContext public section open Lean Lean.Meta namespace Lean.Name private def parseIndexSuffix (s : Substring) : Option Nat := if s.isEmpty then none else if s.front == '_' then s.drop 1 |>.toNat? else none /-- Result type of `Lean.Name.matchUpToIndexSuffix`. See there for details. -/ inductive MatchUpToIndexSuffix /-- Exact match. -/ | exactMatch /-- No match. -/ | noMatch /-- Match up to suffix. -/ | suffixMatch (i : Nat) /-- Succeeds if `n` is equal to `query`, except `n` may have an additional `_i` suffix for some natural number `i`. More specifically: - If `n = query`, the result is `exactMatch`. - If `n = query ++ "_i"` for some natural number `i`, the result is `suffixMatch i`. - Otherwise the result is `noMatch`. -/ def matchUpToIndexSuffix (n : Name) (query : Name) : MatchUpToIndexSuffix := match n, query with | .str pre₁ s₁, .str pre₂ s₂ => if pre₁ != pre₂ then .noMatch else if let some suffix := s₁.dropPrefix? s₂ then if suffix.isEmpty then .exactMatch else if let some i := parseIndexSuffix suffix then .suffixMatch i else .noMatch else .noMatch | n, query => if n == query then .exactMatch else .noMatch end Name namespace LocalContext /-- Obtain the least natural number `i` such that `suggestion ++ "_i"` is an unused name in the given local context. If `suggestion` itself is unused, the result is `none`. -/ def getUnusedUserNameIndex (lctx : LocalContext) (suggestion : Name) : Option Nat := Id.run do let mut minSuffix := none for ldecl in lctx do let hypName := ldecl.userName if hypName.hasMacroScopes then continue match ldecl.userName.matchUpToIndexSuffix suggestion with | .exactMatch => minSuffix := updateMinSuffix minSuffix 1 | .noMatch => continue | .suffixMatch i => minSuffix := updateMinSuffix minSuffix (i + 1) minSuffix where /-- Auxiliary definition for `getUnusedUserNameIndex`. -/ @[inline] updateMinSuffix : Option Nat → Nat → Option Nat | none, j => some j | some i, j => some $ i.max j /-- Obtain a name `n` such that `n` is unused in the given local context and `suggestion` is a prefix of `n`. This is similar to `getUnusedName` but uses a different algorithm which may or may not be faster. -/ def getUnusedUserName (lctx : LocalContext) (suggestion : Name) : Name := let suggestion := suggestion.eraseMacroScopes match lctx.getUnusedUserNameIndex suggestion with | none => suggestion | some i => suggestion.appendIndexAfter i /-- Obtain `n` distinct names such that each name is unused in the given local context and `suggestion` is a prefix of each name. -/ def getUnusedUserNames (lctx : LocalContext) (n : Nat) (suggestion : Name) : Array Name := if n == 0 then #[] else let suggestion := suggestion.eraseMacroScopes let acc := Array.mkEmpty n match lctx.getUnusedUserNameIndex suggestion with | none => loop (acc.push suggestion) (n - 1) 1 | some i => loop acc n i where /-- Auxiliary definition for `getUnusedUserNames`. -/ loop (acc : Array Name) (n i : Nat) : Array Name := match n with | 0 => acc | n + 1 => loop (acc.push $ suggestion.appendIndexAfter i) n (i + 1) end Lean.LocalContext namespace Lean.Meta /-- Obtain a name `n` such that `n` is unused in the current local context and `suggestion` is a prefix of `n`. -/ def getUnusedUserName [Monad m] [MonadLCtx m] (suggestion : Name) : m Name := return (← getLCtx).getUnusedUserName suggestion /-- Obtain `n` distinct names such that each name is unused in the current local context and `suggestion` is a prefix of each name. -/ def getUnusedUserNames [Monad m] [MonadLCtx m] (n : Nat) (suggestion : Name) : m (Array Name) := return (← getLCtx).getUnusedUserNames n suggestion
.lake/packages/batteries/Batteries/Lean/Meta/DiscrTree.lean
module public import Lean.Meta.DiscrTree public import Batteries.Data.Array.Merge public import Batteries.Lean.Meta.Expr public import Batteries.Lean.PersistentHashMap @[expose] public section namespace Lean.Meta.DiscrTree namespace Key /-- Compare two `Key`s. The ordering is total but otherwise arbitrary. (It uses `Name.quickCmp` internally.) -/ protected def cmp : Key → Key → Ordering | .lit v₁, .lit v₂ => compare v₁ v₂ | .fvar n₁ a₁, .fvar n₂ a₂ => n₁.name.quickCmp n₂.name |>.then <| compare a₁ a₂ | .const n₁ a₁, .const n₂ a₂ => n₁.quickCmp n₂ |>.then <| compare a₁ a₂ | .proj s₁ i₁ a₁, .proj s₂ i₂ a₂ => s₁.quickCmp s₂ |>.then <| compare i₁ i₂ |>.then <| compare a₁ a₂ | k₁, k₂ => compare k₁.ctorIdx k₂.ctorIdx instance : Ord Key := ⟨Key.cmp⟩ end Key namespace Trie /-- Merge two `Trie`s. Duplicate values are preserved. -/ partial def mergePreservingDuplicates : Trie α → Trie α → Trie α | node vs₁ cs₁, node vs₂ cs₂ => node (vs₁ ++ vs₂) (mergeChildren cs₁ cs₂) where /-- Auxiliary definition for `mergePreservingDuplicates`. -/ mergeChildren (cs₁ cs₂ : Array (Key × Trie α)) : Array (Key × Trie α) := Array.mergeDedupWith (ord := ⟨compareOn (·.fst)⟩) cs₁ cs₂ (fun (k₁, t₁) (_, t₂) => (k₁, mergePreservingDuplicates t₁ t₂)) end Trie /-- Merge two `DiscrTree`s. Duplicate values are preserved. -/ @[inline] def mergePreservingDuplicates (t u : DiscrTree α) : DiscrTree α := ⟨t.root.mergeWith u.root fun _ trie₁ trie₂ => trie₁.mergePreservingDuplicates trie₂⟩
.lake/packages/batteries/Batteries/Lean/System/IO.lean
module @[expose] public section /-! # Functions for manipulating a list of tasks * `IO.waitAny'` is a wrapper for `IO.waitAny` that also returns the remaining tasks. * `List.waitAll : List (Task α) → Task (List α)` gathers a list of tasks into a task returning the list of all results. -/ set_option autoImplicit true -- duplicated from `lean4/src/Init/System/IO.lean` local macro "nonempty_list" : tactic => `(tactic| exact Nat.zero_lt_succ _) /-- Given a non-empty list of tasks, wait for the first to complete. Return the value and the list of remaining tasks. -/ def IO.waitAny' (tasks : List (Task α)) (h : 0 < tasks.length := by nonempty_list) : BaseIO (α × List (Task α)) := do let (i, a) ← IO.waitAny (tasks.mapIdx fun i t => t.map (prio := .max) fun a => (i, a)) (by simp_all) return (a, tasks.eraseIdx i) /-- Given a list of tasks, create the task returning the list of results, by waiting for each. -/ def List.waitAll (tasks : List (Task α)) : Task (List α) := match tasks with | [] => .pure [] | task :: tasks => task.bind (prio := .max) fun a => tasks.waitAll.map (prio := .max) fun as => a :: as
.lake/packages/batteries/Batteries/Util/LibraryNote.lean
module public meta import Lean.Elab.Command public meta section /-! # Define the `library_note` command. -/ namespace Batteries.Util.LibraryNote open Lean /-- A library note consists of a (short) tag and a (long) note. -/ @[expose] def LibraryNoteEntry := String × String deriving Inhabited /-- Environment extension supporting `library_note`. -/ initialize libraryNoteExt : SimplePersistentEnvExtension LibraryNoteEntry (Array LibraryNoteEntry) ← registerSimplePersistentEnvExtension { addEntryFn := Array.push addImportedFn := Array.flatMap id } open Lean Parser Command in /-- ``` library_note "some tag" /-- ... some explanation ... -/ ``` creates a new "library note", which can then be cross-referenced using ``` -- See note [some tag] ``` in doc-comments. Use `#help note "some tag"` to display all notes with the tag `"some tag"` in the infoview. This command can be imported from Batteries.Tactic.HelpCmd . -/ elab "library_note " title:strLit ppSpace text:docComment : command => do modifyEnv (libraryNoteExt.addEntry · (title.getString, text.getDocString))
.lake/packages/batteries/Batteries/Util/Cache.lean
module public import Lean.Meta.DiscrTree @[expose] public section /-! # Once-per-file cache for tactics This file defines cache data structures for tactics that are initialized the first time they are accessed. Since Lean 4 starts one process per file, these caches are once-per-file and can for example be used to cache information about the imported modules. The `Cache α` data structure is the most generic version we define. It is created using `Cache.mk f` where `f : MetaM α` performs the initialization of the cache: ``` initialize numberOfImports : Cache Nat ← Cache.mk do (← getEnv).imports.size -- (does not work in the same module where the cache is defined) #eval show MetaM Nat from numberOfImports.get ``` The `DeclCache α` data structure computes a fold over the environment's constants: `DeclCache.mk empty f` constructs such a cache where `empty : α` and `f : Name → ConstantInfo → α → MetaM α`. The result of the constants in the imports is cached between tactic invocations, while for constants defined in the same file `f` is evaluated again every time. This kind of cache can be used e.g. to populate discrimination trees. -/ open Lean Meta namespace Batteries.Tactic /-- Once-per-file cache. -/ def Cache (α : Type) := IO.Ref <| MetaM α ⊕ Task (Except Exception α) -- This instance is required as we use `Cache` with `initialize`. -- One might expect an `Inhabited` instance here, -- but there is no way to construct such without using choice anyway. instance : Nonempty (Cache α) := inferInstanceAs <| Nonempty (IO.Ref _) /-- Creates a cache with an initialization function. -/ def Cache.mk (init : MetaM α) : IO (Cache α) := IO.mkRef <| Sum.inl init /-- Access the cache. Calling this function for the first time will initialize the cache with the function provided in the constructor. -/ def Cache.get [Monad m] [MonadEnv m] [MonadLog m] [MonadOptions m] [MonadLiftT BaseIO m] [MonadExcept Exception m] (cache : Cache α) : m α := do let t ← match ← ST.Ref.get (m := BaseIO) cache with | .inr t => pure t | .inl init => let env ← getEnv let fileName ← getFileName let fileMap ← getFileMap let options ← getOptions -- TODO: sanitize options? -- Default heartbeats to a reasonable value. -- otherwise exact? times out on mathlib -- TODO: add customization option let options := maxHeartbeats.set options <| options.get? maxHeartbeats.name |>.getD 1000000 let res ← EIO.asTask <| init {} |>.run' {} { options, fileName, fileMap } |>.run' { env } cache.set (m := BaseIO) (.inr res) pure res match t.get with | Except.ok res => pure res | Except.error err => throw err /-- Cached fold over the environment's declarations, where a given function is applied to `α` for every constant. -/ structure DeclCache (α : Type) where mk' :: /-- The cached data. -/ cache : Cache α /-- Function for adding a declaration from the current file to the cache. -/ addDecl : Name → ConstantInfo → α → MetaM α /-- Function for adding a declaration from the library to the cache. Defaults to the same behaviour as adding a declaration from the current file. -/ addLibraryDecl : Name → ConstantInfo → α → MetaM α := addDecl deriving Nonempty /-- Creates a `DeclCache`. First, if `pre` is nonempty, run that for a value, and if successful populate the cache with that value. If `pre` is empty, or it fails, the cached structure `α` is initialized with `empty`, and then `addLibraryDecl` is called for every imported constant. After all imported constants have been added, we run `post`. Finally, the result is cached. When `get` is called, `addDecl` is also called for every constant in the current file. -/ def DeclCache.mk (profilingName : String) (pre : MetaM α := failure) (empty : α) (addDecl : Name → ConstantInfo → α → MetaM α) (addLibraryDecl : Name → ConstantInfo → α → MetaM α := addDecl) (post : α → MetaM α := fun a => pure a) : IO (DeclCache α) := do let cache ← Cache.mk do try -- We allow arbitrary failures in the `pre` tactic, -- and fall back on folding over the entire environment. -- In practice the `pre` tactic may be unpickling an `.olean`, -- and may fail after leanprover/lean4#2766 because the embedded hash is incorrect. pre catch _ => profileitM Exception profilingName (← getOptions) do post <|← (← getEnv).constants.map₁.foldM (init := empty) fun a n c => addLibraryDecl n c a pure { cache, addDecl } /-- Access the cache. Calling this function for the first time will initialize the cache with the function provided in the constructor. -/ def DeclCache.get (cache : DeclCache α) : MetaM α := do (← getEnv).constants.map₂.foldlM (init := ← cache.cache.get) fun a n c => cache.addDecl n c a /-- A type synonym for a `DeclCache` containing a pair of discrimination trees. The first will store declarations in the current file, the second will store declarations from imports (and will hopefully be "read-only" after creation). -/ @[reducible] def DiscrTreeCache (α : Type) : Type := DeclCache (DiscrTree α × DiscrTree α) /-- Build a `DiscrTreeCache`, from a function that returns a collection of keys and values for each declaration. -/ def DiscrTreeCache.mk [BEq α] (profilingName : String) (processDecl : Name → ConstantInfo → MetaM (Array (Array DiscrTree.Key × α))) (post? : Option (Array α → Array α) := none) (init : MetaM (DiscrTree α) := failure) : IO (DiscrTreeCache α) := let updateTree := fun name constInfo tree => do return (← processDecl name constInfo).foldl (init := tree) fun t (k, v) => t.insertCore k v let addDecl := fun name constInfo (tree₁, tree₂) => return (← updateTree name constInfo tree₁, tree₂) let addLibraryDecl := fun name constInfo (tree₁, tree₂) => return (tree₁, ← updateTree name constInfo tree₂) let post := match post? with | some f => fun (T₁, T₂) => return (T₁, T₂.mapArrays f) | none => fun T => pure T let init' := return ({}, ← init) DeclCache.mk profilingName init' ({}, {}) addDecl addLibraryDecl (post := post) /-- Get matches from both the discrimination tree for declarations in the current file, and for the imports. Note that if you are calling this multiple times with the same environment, it will rebuild the discrimination tree for the current file multiple times, and it would be more efficient to call `c.get` once, and then call `DiscrTree.getMatch` multiple times. -/ def DiscrTreeCache.getMatch (c : DiscrTreeCache α) (e : Expr) : MetaM (Array α) := do let (locals, imports) ← c.get -- `DiscrTree.getMatch` returns results in batches, with more specific lemmas coming later. -- Hence we reverse this list, so we try out more specific lemmas earlier. return (← locals.getMatch e).reverse ++ (← imports.getMatch e).reverse
.lake/packages/batteries/Batteries/Util/Pickle.lean
module public import Lean.Environment @[expose] public section /-! # Pickling and unpickling objects By abusing `saveModuleData` and `readModuleData` we can pickle and unpickle objects to disk. -/ open Lean System /-- Save an object to disk. If you need to write multiple objects from within a single declaration, you will need to provide a unique `key` for each. -/ def pickle {α : Type} (path : FilePath) (x : α) (key : Name := by exact decl_name%) : IO Unit := saveModuleData path key (unsafe unsafeCast x) /-- Load an object from disk. Note: The returned `CompactedRegion` can be used to free the memory behind the value of type `α`, using `CompactedRegion.free` (which is only safe once all references to the `α` are released). Ignoring the `CompactedRegion` results in the data being leaked. Use `withUnpickle` to call `CompactedRegion.free` automatically. This function is unsafe because the data being loaded may not actually have type `α`, and this may cause crashes or other bad behavior. -/ unsafe def unpickle (α : Type) (path : FilePath) : IO (α × CompactedRegion) := do let (x, region) ← readModuleData path pure (unsafeCast x, region) /-- Load an object from disk and run some continuation on it, freeing memory afterwards. -/ unsafe def withUnpickle [Monad m] [MonadLiftT IO m] {α β : Type} (path : FilePath) (f : α → m β) : m β := do let (x, region) ← unpickle α path let r ← f x region.free pure r
.lake/packages/batteries/Batteries/Util/ExtendedBinder.lean
module @[expose] public section /-! Defines an extended binder syntax supporting `∀ ε > 0, ...` etc. -/ namespace Batteries.ExtendedBinder open Lean -- We also provide special versions of ∀/∃ that take a list of extended binders. -- The built-in binders are not reused because that results in overloaded syntax. /-- An extended binder has the form `x`, `x : ty`, or `x pred` where `pred` is a `binderPred` like `< 2`. -/ syntax extBinder := binderIdent ((" : " term) <|> binderPred)? /-- A extended binder in parentheses -/ syntax extBinderParenthesized := " (" extBinder ")" -- TODO: inlining this definition breaks /-- A list of parenthesized binders -/ syntax extBinderCollection := extBinderParenthesized* /-- A single (unparenthesized) binder, or a list of parenthesized binders -/ syntax extBinders := (ppSpace extBinder) <|> extBinderCollection /-- The syntax `∃ᵉ (x < 2) (y < 3), p x y` is shorthand for `∃ x < 2, ∃ y < 3, p x y`. -/ syntax "∃ᵉ" extBinders ", " term : term macro_rules | `(∃ᵉ, $b) => pure b | `(∃ᵉ ($p:extBinder) $[($ps:extBinder)]*, $b) => `(∃ᵉ $p:extBinder, ∃ᵉ $[($ps:extBinder)]*, $b) macro_rules -- TODO: merging the two macro_rules breaks expansion | `(∃ᵉ $x:binderIdent, $b) => `(∃ $x:binderIdent, $b) | `(∃ᵉ $x:binderIdent : $ty:term, $b) => `(∃ $x:binderIdent : $ty:term, $b) | `(∃ᵉ $x:binderIdent $p:binderPred, $b) => `(∃ $x:binderIdent $p:binderPred, $b) /-- The syntax `∀ᵉ (x < 2) (y < 3), p x y` is shorthand for `∀ x < 2, ∀ y < 3, p x y`. -/ syntax "∀ᵉ" extBinders ", " term : term macro_rules | `(∀ᵉ, $b) => pure b | `(∀ᵉ ($p:extBinder) $[($ps:extBinder)]*, $b) => `(∀ᵉ $p:extBinder, ∀ᵉ $[($ps:extBinder)]*, $b) macro_rules -- TODO: merging the two macro_rules breaks expansion | `(∀ᵉ _, $b) => `(∀ _, $b) | `(∀ᵉ $x:ident, $b) => `(∀ $x:ident, $b) | `(∀ᵉ _ : $ty:term, $b) => `(∀ _ : $ty:term, $b) | `(∀ᵉ $x:ident : $ty:term, $b) => `(∀ $x:ident : $ty:term, $b) | `(∀ᵉ $x:binderIdent $p:binderPred, $b) => `(∀ $x:binderIdent $p:binderPred, $b)
.lake/packages/batteries/Batteries/Util/ProofWanted.lean
module public meta import Lean.Elab.Exception public meta import Lean.Elab.Command public meta section open Lean Parser Elab Command /-- This proof would be a welcome contribution to the library! The syntax of `proof_wanted` declarations is just like that of `theorem`, but without `:=` or the proof. Lean checks that `proof_wanted` declarations are well-formed (e.g. it ensures that all the mentioned names are in scope, and that the theorem statement is a valid proposition), but they are discarded afterwards. This means that they cannot be used as axioms. Typical usage: ``` @[simp] proof_wanted empty_find? [BEq α] [Hashable α] {a : α} : (∅ : HashMap α β).find? a = none ``` -/ @[command_parser] def «proof_wanted» := leading_parser declModifiers false >> "proof_wanted" >> declId >> ppIndent declSig /-- Elaborate a `proof_wanted` declaration. The declaration is translated to an axiom during elaboration, but it's then removed from the environment. -/ @[command_elab «proof_wanted»] def elabProofWanted : CommandElab | `($mods:declModifiers proof_wanted $name $args* : $res) => withoutModifyingEnv do -- The helper axiom is used instead of `sorry` to avoid spurious warnings elabCommand <| ← `( section set_option linter.unusedVariables false axiom helper {α : Sort _} : α $mods:declModifiers theorem $name $args* : $res := helper end) | _ => throwUnsupportedSyntax
.lake/packages/batteries/Batteries/Util/Panic.lean
module @[expose] public section namespace Batteries /-- Panic with a specific default value `v`. -/ def panicWith (v : α) (msg : String) : α := @panic α ⟨v⟩ msg @[simp] theorem panicWith_eq (v : α) (msg) : panicWith v msg = v := rfl
.lake/packages/batteries/Batteries/Linter/UnnecessarySeqFocus.lean
module public meta import Lean.Elab.Command public meta import Batteries.Lean.AttributeExtra public meta import Lean.Linter.Basic public meta section namespace Batteries.Linter open Lean Elab Command Linter Std /-- Enables the 'unnecessary `<;>`' linter. This will warn whenever the `<;>` tactic combinator is used when `;` would work. ``` example : True := by apply id <;> trivial ``` The `<;>` is unnecessary here because `apply id` only makes one subgoal. Prefer `apply id; trivial` instead. In some cases, the `<;>` is syntactically necessary because a single tactic is expected: ``` example : True := by cases () with apply id <;> apply id | unit => trivial ``` In this case, you should use parentheses, as in `(apply id; apply id)`: ``` example : True := by cases () with (apply id; apply id) | unit => trivial ``` -/ register_option linter.unnecessarySeqFocus : Bool := { defValue := true descr := "enable the 'unnecessary <;>' linter" } example : True := by cases () with apply id <;> apply id | unit => trivial namespace UnnecessarySeqFocus /-- Gets the value of the `linter.unnecessarySeqFocus` option. -/ def getLinterUnnecessarySeqFocus (o : LinterOptions) : Bool := getLinterValue linter.unnecessarySeqFocus o /-- The `multigoal` attribute keeps track of tactics that operate on multiple goals, meaning that `tac` acts differently from `focus tac`. This is used by the 'unnecessary `<;>`' linter to prevent false positives where `tac <;> tac'` cannot be replaced by `(tac; tac')` because the latter would expose `tac` to a different set of goals. -/ initialize multigoalAttr : TagAttributeExtra ← registerTagAttributeExtra `multigoal "this tactic acts on multiple goals" [ ``Parser.Tactic.«tacticNext_=>_», ``Parser.Tactic.allGoals, ``Parser.Tactic.anyGoals, ``Parser.Tactic.case, ``Parser.Tactic.case', ``Parser.Tactic.Conv.«convNext__=>_», ``Parser.Tactic.Conv.allGoals, ``Parser.Tactic.Conv.anyGoals, ``Parser.Tactic.Conv.case, ``Parser.Tactic.Conv.case', ``Parser.Tactic.rotateLeft, ``Parser.Tactic.rotateRight, ``Parser.Tactic.show, ``Parser.Tactic.tacticStop_ ] /-- The information we record for each `<;>` node appearing in the syntax. -/ structure Entry where /-- The `<;>` node itself. -/ stx : Syntax /-- * `true`: this `<;>` has been used unnecessarily at least once * `false`: it has never been executed * If it has been used properly at least once, the entry is removed from the table. -/ used : Bool /-- The monad for collecting used tactic syntaxes. -/ abbrev M (ω) := StateRefT (Std.HashMap String.Range Entry) (ST ω) /-- True if this is a `<;>` node in either `tactic` or `conv` classes. -/ @[inline] def isSeqFocus (k : SyntaxNodeKind) : Bool := k == ``Parser.Tactic.«tactic_<;>_» || k == ``Parser.Tactic.Conv.«conv_<;>_» /-- Accumulates the set of tactic syntaxes that should be evaluated at least once. -/ @[specialize] partial def getTactics {ω} (stx : Syntax) : M ω Unit := do if let .node _ k args := stx then if isSeqFocus k then let r := stx.getRange? true if let some r := r then modify fun m => m.insert r { stx, used := false } args.forM getTactics /-- Traverse the info tree down a given path. Each `(n, i)` means that the array must have length `n` and we will descend into the `i`'th child. -/ def getPath : Info → PersistentArray InfoTree → List ((n : Nat) × Fin n) → Option Info | i, _, [] => some i | _, c, ⟨n, i, h⟩::ns => if e : c.size = n then if let .node i c' := c[i] then getPath i c' ns else none else none mutual variable (env : Environment) /-- Search for tactic executions in the info tree and remove executed tactic syntaxes. -/ partial def markUsedTacticsList (trees : PersistentArray InfoTree) : M ω Unit := trees.forM markUsedTactics /-- Search for tactic executions in the info tree and remove executed tactic syntaxes. -/ partial def markUsedTactics : InfoTree → M ω Unit | .node i c => do if let .ofTacticInfo i := i then if let some r := i.stx.getRange? true then if let some entry := (← get)[r]? then if i.stx.getKind == ``Parser.Tactic.«tactic_<;>_» then let isBad := do unless i.goalsBefore.length == 1 || !multigoalAttr.hasTag env i.stx[0].getKind do none -- Note: this uses the exact sequence of tactic applications -- in the macro expansion of `<;> : tactic` let .ofTacticInfo i ← getPath (.ofTacticInfo i) c [⟨1, 0⟩, ⟨2, 1⟩, ⟨1, 0⟩, ⟨5, 0⟩] | none guard <| i.goalsAfter.length == 1 modify fun s => if isBad.isSome then s.insert r { entry with used := true } else s.erase r else if i.stx.getKind == ``Parser.Tactic.Conv.«conv_<;>_» then let isBad := do unless i.goalsBefore.length == 1 || !multigoalAttr.hasTag env i.stx[0].getKind do none -- Note: this uses the exact sequence of tactic applications -- in the macro expansion of `<;> : conv` let .ofTacticInfo i ← getPath (.ofTacticInfo i) c [⟨1, 0⟩, ⟨1, 0⟩, ⟨1, 0⟩, ⟨1, 0⟩, ⟨1, 0⟩, ⟨2, 1⟩, ⟨1, 0⟩, ⟨5, 0⟩] | none guard <| i.goalsAfter.length == 1 modify fun s => if isBad.isSome then s.insert r { entry with used := true } else s.erase r markUsedTacticsList c | .context _ t => markUsedTactics t | .hole _ => pure () end @[inherit_doc Batteries.Linter.linter.unnecessarySeqFocus] def unnecessarySeqFocusLinter : Linter where run := withSetOptionIn fun stx => do unless getLinterUnnecessarySeqFocus (← getLinterOptions) && (← getInfoState).enabled do return if (← get).messages.hasErrors then return let trees ← getInfoTrees let env ← getEnv let go {ω} : M ω Unit := do getTactics stx markUsedTacticsList env trees let (_, map) := runST fun _ => go.run {} let unused := map.fold (init := #[]) fun acc r { stx, used } => if used then acc.push (stx[1].getRange?.getD r, stx[1]) else acc let key (r : String.Range) := (r.start.byteIdx, (-r.stop.byteIdx : Int)) let mut last : String.Range := ⟨0, 0⟩ for (r, stx) in let _ := @lexOrd; let _ := @ltOfOrd.{0}; unused.qsort (key ·.1 < key ·.1) do if last.start ≤ r.start && r.stop ≤ last.stop then continue logLint linter.unnecessarySeqFocus stx "Used `tac1 <;> tac2` where `(tac1; tac2)` would suffice" last := r initialize addLinter unnecessarySeqFocusLinter
.lake/packages/batteries/Batteries/Linter/UnreachableTactic.lean
module public meta import Lean.Elab.Command public meta import Lean.Parser.Syntax public meta import Batteries.Tactic.Unreachable public meta import Lean.Linter.Basic public meta section namespace Batteries.Linter open Lean Elab Command Linter Std /-- Enables the 'unreachable tactic' linter. This will warn on any tactics that are never executed. For example, in `example : True := by trivial <;> done`, the tactic `done` is never executed because `trivial` produces no subgoals; you could put `sorry` or `apply I_don't_exist` or anything else there and no error would result. A common source of such things is `simp <;> tac` in the case that `simp` improves and closes a subgoal that was previously being closed by `tac`. -/ register_option linter.unreachableTactic : Bool := { defValue := true descr := "enable the 'unreachable tactic' linter" } namespace UnreachableTactic /-- Gets the value of the `linter.unreachableTactic` option. -/ def getLinterUnreachableTactic (o : LinterOptions) : Bool := getLinterValue linter.unreachableTactic o /-- The monad for collecting used tactic syntaxes. -/ abbrev M := StateRefT (Std.HashMap String.Range Syntax) IO /-- A list of blacklisted syntax kinds, which are expected to have subterms that contain unevaluated tactics. -/ initialize ignoreTacticKindsRef : IO.Ref NameHashSet ← IO.mkRef <| (∅ : NameHashSet) |>.insert ``Parser.Term.binderTactic |>.insert ``Lean.Parser.Term.dynamicQuot |>.insert ``Lean.Parser.Tactic.quotSeq |>.insert ``Lean.Parser.Tactic.tacticStop_ |>.insert ``Lean.Parser.Command.notation |>.insert ``Lean.Parser.Command.mixfix |>.insert ``Lean.Parser.Tactic.discharger /-- Is this a syntax kind that contains intentionally unevaluated tactic subterms? -/ def isIgnoreTacticKind (ignoreTacticKinds : NameHashSet) (k : SyntaxNodeKind) : Bool := match k with | .str _ "quot" => true | _ => ignoreTacticKinds.contains k /-- Adds a new syntax kind whose children will be ignored by the `unreachableTactic` linter. This should be called from an `initialize` block. -/ def addIgnoreTacticKind (kind : SyntaxNodeKind) : IO Unit := ignoreTacticKindsRef.modify (·.insert kind) variable (ignoreTacticKinds : NameHashSet) (isTacKind : SyntaxNodeKind → Bool) in /-- Accumulates the set of tactic syntaxes that should be evaluated at least once. -/ @[specialize] partial def getTactics (stx : Syntax) : M Unit := do if let .node _ k args := stx then if !isIgnoreTacticKind ignoreTacticKinds k then args.forM getTactics if isTacKind k then if let some r := stx.getRange? true then modify fun m => m.insert r stx mutual variable (isTacKind : SyntaxNodeKind → Bool) /-- Search for tactic executions in the info tree and remove executed tactic syntaxes. -/ partial def eraseUsedTacticsList (trees : PersistentArray InfoTree) : M Unit := trees.forM eraseUsedTactics /-- Search for tactic executions in the info tree and remove executed tactic syntaxes. -/ partial def eraseUsedTactics : InfoTree → M Unit | .node i c => do if let .ofTacticInfo i := i then if let some r := i.stx.getRange? true then modify (·.erase r) eraseUsedTacticsList c | .context _ t => eraseUsedTactics t | .hole _ => pure () end @[inherit_doc Batteries.Linter.linter.unreachableTactic] def unreachableTacticLinter : Linter where run := withSetOptionIn fun stx => do unless getLinterUnreachableTactic (← getLinterOptions) && (← getInfoState).enabled do return if (← get).messages.hasErrors then return let cats := (Parser.parserExtension.getState (← getEnv)).categories -- These lookups may fail when the linter is run in a fresh, empty environment let some tactics := Parser.ParserCategory.kinds <$> cats.find? `tactic | return let some convs := Parser.ParserCategory.kinds <$> cats.find? `conv | return let trees ← getInfoTrees let go : M Unit := do getTactics (← ignoreTacticKindsRef.get) (fun k => tactics.contains k || convs.contains k) stx eraseUsedTacticsList trees let (_, map) ← go.run {} let unreachable := map.toArray let key (r : String.Range) := (r.start.byteIdx, (-r.stop.byteIdx : Int)) let mut last : String.Range := ⟨0, 0⟩ for (r, stx) in let _ := @lexOrd; let _ := @ltOfOrd.{0}; unreachable.qsort (key ·.1 < key ·.1) do if stx.getKind ∈ [``Batteries.Tactic.unreachable, ``Batteries.Tactic.unreachableConv] then continue if last.start ≤ r.start && r.stop ≤ last.stop then continue logLint linter.unreachableTactic stx "this tactic is never executed" last := r initialize addLinter unreachableTacticLinter
.lake/packages/batteries/Batteries/Classes/Deprecated.lean
module public import Batteries.Classes.Order @[expose] public section /-! Deprecated Batteries comparison classes Examples are to ensure that old instances have equivalent new instances. -/ set_option linter.deprecated false namespace Batteries /-- `OrientedCmp cmp` asserts that `cmp` is determined by the relation `cmp x y = .lt`. -/ @[deprecated Std.OrientedCmp (since := "2025-07-01")] class OrientedCmp (cmp : α → α → Ordering) : Prop where /-- The comparator operation is symmetric, in the sense that if `cmp x y` equals `.lt` then `cmp y x = .gt` and vice versa. -/ symm (x y) : (cmp x y).swap = cmp y x attribute [deprecated Std.OrientedOrd.eq_swap (since := "2025-07-01")] OrientedCmp.symm namespace OrientedCmp @[deprecated Std.OrientedCmp.gt_iff_lt (since := "2025-07-01")] theorem cmp_eq_gt [OrientedCmp cmp] : cmp x y = .gt ↔ cmp y x = .lt := by rw [← Ordering.swap_inj, symm]; exact .rfl @[deprecated Std.OrientedCmp.le_iff_ge (since := "2025-07-01")] theorem cmp_ne_gt [OrientedCmp cmp] : cmp x y ≠ .gt ↔ cmp y x ≠ .lt := not_congr cmp_eq_gt @[deprecated Std.OrientedCmp.eq_comm (since := "2025-07-01")] theorem cmp_eq_eq_symm [OrientedCmp cmp] : cmp x y = .eq ↔ cmp y x = .eq := by rw [← Ordering.swap_inj, symm]; exact .rfl @[deprecated Std.ReflCmp.compare_self (since := "2025-07-01")] theorem cmp_refl [OrientedCmp cmp] : cmp x x = .eq := match e : cmp x x with | .lt => nomatch e.symm.trans (cmp_eq_gt.2 e) | .eq => rfl | .gt => nomatch (cmp_eq_gt.1 e).symm.trans e @[deprecated Std.OrientedCmp.not_lt_of_lt (since := "2025-07-01")] theorem lt_asymm [OrientedCmp cmp] (h : cmp x y = .lt) : cmp y x ≠ .lt := fun h' => nomatch h.symm.trans (cmp_eq_gt.2 h') @[deprecated Std.OrientedCmp.not_gt_of_gt (since := "2025-07-01")] theorem gt_asymm [OrientedCmp cmp] (h : cmp x y = .gt) : cmp y x ≠ .gt := mt cmp_eq_gt.1 <| lt_asymm <| cmp_eq_gt.1 h end OrientedCmp /-- `TransCmp cmp` asserts that `cmp` induces a transitive relation. -/ @[deprecated Std.TransCmp (since := "2025-07-01")] class TransCmp (cmp : α → α → Ordering) : Prop extends OrientedCmp cmp where /-- The comparator operation is transitive. -/ le_trans : cmp x y ≠ .gt → cmp y z ≠ .gt → cmp x z ≠ .gt attribute [deprecated Std.TransCmp.le_trans (since := "2025-07-01")] TransCmp.le_trans namespace TransCmp variable [TransCmp cmp] open OrientedCmp Decidable @[deprecated Std.TransCmp.ge_trans (since := "2025-07-01")] theorem ge_trans (h₁ : cmp x y ≠ .lt) (h₂ : cmp y z ≠ .lt) : cmp x z ≠ .lt := by have := @TransCmp.le_trans _ cmp _ z y x simp [cmp_eq_gt] at *; exact this h₂ h₁ @[deprecated Std.TransCmp.lt_of_le_of_lt (since := "2025-07-01")] theorem le_lt_trans (h₁ : cmp x y ≠ .gt) (h₂ : cmp y z = .lt) : cmp x z = .lt := byContradiction fun h₃ => ge_trans (mt cmp_eq_gt.2 h₁) h₃ h₂ @[deprecated Std.TransCmp.lt_of_lt_of_le (since := "2025-07-01")] theorem lt_le_trans (h₁ : cmp x y = .lt) (h₂ : cmp y z ≠ .gt) : cmp x z = .lt := byContradiction fun h₃ => ge_trans h₃ (mt cmp_eq_gt.2 h₂) h₁ @[deprecated Std.TransCmp.lt_trans (since := "2025-07-01")] theorem lt_trans (h₁ : cmp x y = .lt) (h₂ : cmp y z = .lt) : cmp x z = .lt := le_lt_trans (gt_asymm <| cmp_eq_gt.2 h₁) h₂ @[deprecated Std.TransCmp.gt_trans (since := "2025-07-01")] theorem gt_trans (h₁ : cmp x y = .gt) (h₂ : cmp y z = .gt) : cmp x z = .gt := by rw [cmp_eq_gt] at h₁ h₂ ⊢; exact lt_trans h₂ h₁ @[deprecated Std.TransCmp.congr_left (since := "2025-07-01")] theorem cmp_congr_left (xy : cmp x y = .eq) : cmp x z = cmp y z := match yz : cmp y z with | .lt => byContradiction (ge_trans (nomatch ·.symm.trans (cmp_eq_eq_symm.1 xy)) · yz) | .gt => byContradiction (le_trans (nomatch ·.symm.trans (cmp_eq_eq_symm.1 xy)) · yz) | .eq => match xz : cmp x z with | .lt => nomatch ge_trans (nomatch ·.symm.trans xy) (nomatch ·.symm.trans yz) xz | .gt => nomatch le_trans (nomatch ·.symm.trans xy) (nomatch ·.symm.trans yz) xz | .eq => rfl @[deprecated Std.TransCmp.congr_left (since := "2025-07-01")] theorem cmp_congr_left' (xy : cmp x y = .eq) : cmp x = cmp y := funext fun _ => cmp_congr_left xy @[deprecated Std.TransCmp.congr_right (since := "2025-07-01")] theorem cmp_congr_right (yz : cmp y z = .eq) : cmp x y = cmp x z := by rw [← Ordering.swap_inj, symm, symm, cmp_congr_left yz] end TransCmp instance [inst : OrientedCmp cmp] : OrientedCmp (flip cmp) where symm _ _ := inst.symm .. example [inst : Std.OrientedCmp cmp] : Std.OrientedCmp (flip cmp) := inferInstance instance [inst : TransCmp cmp] : TransCmp (flip cmp) where le_trans h1 h2 := inst.le_trans h2 h1 example [inst : Std.TransCmp cmp] : Std.TransCmp (flip cmp) := inferInstance /-- `BEqCmp cmp` asserts that `cmp x y = .eq` and `x == y` coincide. -/ @[deprecated Std.LawfulBEqCmp (since := "2025-07-01")] class BEqCmp [BEq α] (cmp : α → α → Ordering) : Prop where /-- `cmp x y = .eq` holds iff `x == y` is true. -/ cmp_iff_beq : cmp x y = .eq ↔ x == y attribute [deprecated Std.LawfulBEqCmp.compare_eq_iff_beq (since := "2025-07-01")] BEqCmp.cmp_iff_beq @[deprecated Std.LawfulEqCmp.compare_eq_iff_eq (since := "2025-07-01")] theorem BEqCmp.cmp_iff_eq [BEq α] [LawfulBEq α] [BEqCmp (α := α) cmp] : cmp x y = .eq ↔ x = y := by simp [BEqCmp.cmp_iff_beq] /-- `LTCmp cmp` asserts that `cmp x y = .lt` and `x < y` coincide. -/ @[deprecated Std.LawfulLTCmp (since := "2025-07-01")] class LTCmp [LT α] (cmp : α → α → Ordering) : Prop extends OrientedCmp cmp where /-- `cmp x y = .lt` holds iff `x < y` is true. -/ cmp_iff_lt : cmp x y = .lt ↔ x < y attribute [deprecated Std.LawfulLTCmp.eq_lt_iff_lt (since := "2025-07-01")] LTCmp.cmp_iff_lt @[deprecated Std.LawfulLTCmp.eq_gt_iff_gt (since := "2025-07-01")] theorem LTCmp.cmp_iff_gt [LT α] [LTCmp (α := α) cmp] : cmp x y = .gt ↔ y < x := by rw [OrientedCmp.cmp_eq_gt, LTCmp.cmp_iff_lt] /-- `LECmp cmp` asserts that `cmp x y ≠ .gt` and `x ≤ y` coincide. -/ @[deprecated Std.LawfulLECmp (since := "2025-07-01")] class LECmp [LE α] (cmp : α → α → Ordering) : Prop extends OrientedCmp cmp where /-- `cmp x y ≠ .gt` holds iff `x ≤ y` is true. -/ cmp_iff_le : cmp x y ≠ .gt ↔ x ≤ y attribute [deprecated Std.LawfulLECmp.ne_gt_iff_le (since := "2025-07-01")] LECmp.cmp_iff_le @[deprecated Std.LawfulLECmp.ne_lt_iff_ge (since := "2025-07-01")] theorem LECmp.cmp_iff_ge [LE α] [LECmp (α := α) cmp] : cmp x y ≠ .lt ↔ y ≤ x := by rw [← OrientedCmp.cmp_ne_gt, LECmp.cmp_iff_le] /-- `LawfulCmp cmp` asserts that the `LE`, `LT`, `BEq` instances are all coherent with each other and with `cmp`, describing a strict weak order (a linear order except for antisymmetry). -/ @[deprecated Std.LawfulBCmp (since := "2025-07-01")] class LawfulCmp [LE α] [LT α] [BEq α] (cmp : α → α → Ordering) : Prop extends TransCmp cmp, BEqCmp cmp, LTCmp cmp, LECmp cmp /-- `OrientedOrd α` asserts that the `Ord` instance satisfies `OrientedCmp`. -/ @[deprecated Std.OrientedOrd (since := "2025-07-01")] abbrev OrientedOrd (α) [Ord α] := OrientedCmp (α := α) compare /-- `TransOrd α` asserts that the `Ord` instance satisfies `TransCmp`. -/ @[deprecated Std.TransOrd (since := "2025-07-01")] abbrev TransOrd (α) [Ord α] := TransCmp (α := α) compare /-- `BEqOrd α` asserts that the `Ord` and `BEq` instances are coherent via `BEqCmp`. -/ @[deprecated Std.LawfulBEqOrd (since := "2025-07-01")] abbrev BEqOrd (α) [BEq α] [Ord α] := BEqCmp (α := α) compare /-- `LTOrd α` asserts that the `Ord` instance satisfies `LTCmp`. -/ @[deprecated Std.LawfulLTOrd (since := "2025-07-01")] abbrev LTOrd (α) [LT α] [Ord α] := LTCmp (α := α) compare /-- `LEOrd α` asserts that the `Ord` instance satisfies `LECmp`. -/ @[deprecated Std.LawfulLEOrd (since := "2025-07-01")] abbrev LEOrd (α) [LE α] [Ord α] := LECmp (α := α) compare /-- `LawfulOrd α` asserts that the `Ord` instance satisfies `LawfulCmp`. -/ @[deprecated Std.LawfulBOrd (since := "2025-07-01")] abbrev LawfulOrd (α) [LE α] [LT α] [BEq α] [Ord α] := LawfulCmp (α := α) compare @[deprecated Std.TransCmp.compareOfLessAndEq_of_irrefl_of_trans_of_antisymm (since := "2025-07-01")] protected theorem TransCmp.compareOfLessAndEq [LT α] [DecidableRel (LT.lt (α := α))] [DecidableEq α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (lt_antisymm : ∀ {x y : α}, ¬x < y → ¬y < x → x = y) : TransCmp (α := α) (compareOfLessAndEq · ·) := by have : OrientedCmp (α := α) (compareOfLessAndEq · ·) := by refine { symm := fun x y => ?_ } simp [compareOfLessAndEq]; split <;> [rename_i xy; split <;> [subst y; rename_i xy ne]] · rw [if_neg, if_neg]; rfl · rintro rfl; exact lt_irrefl _ xy · exact fun yx => lt_irrefl _ (lt_trans xy yx) · rw [if_neg ‹_›, if_pos rfl]; rfl · split <;> [rfl; rename_i yx] cases ne (lt_antisymm xy yx) refine { this with le_trans := fun {x y z} yx zy => ?_ } rw [Ne, this.cmp_eq_gt, compareOfLessAndEq_eq_lt] at yx zy ⊢ intro zx if xy : x < y then exact zy (lt_trans zx xy) else exact zy (lt_antisymm yx xy ▸ zx) @[deprecated Std.TransCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (since := "2025-07-01")] theorem TransCmp.compareOfLessAndEq_of_le [LT α] [LE α] [DecidableRel (LT.lt (α := α))] [DecidableEq α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (not_lt : ∀ {x y : α}, ¬x < y → y ≤ x) (le_antisymm : ∀ {x y : α}, x ≤ y → y ≤ x → x = y) : TransCmp (α := α) (compareOfLessAndEq · ·) := .compareOfLessAndEq lt_irrefl lt_trans fun xy yx => le_antisymm (not_lt yx) (not_lt xy) @[deprecated Std.LawfulBEqCmp.compareOfLessAndEq_of_lt_irrefl (since := "2025-07-01")] protected theorem BEqCmp.compareOfLessAndEq [LT α] [DecidableRel (LT.lt (α := α))] [DecidableEq α] [BEq α] [LawfulBEq α] (lt_irrefl : ∀ x : α, ¬x < x) : BEqCmp (α := α) (compareOfLessAndEq · ·) where cmp_iff_beq {x y} := by simp [compareOfLessAndEq] split <;> [skip; split] <;> simp [*] rintro rfl; exact lt_irrefl _ ‹_› @[deprecated Std.LawfulLTCmp.compareOfLessAndEq_of_irrefl_of_trans_of_antisymm (since := "2025-07-01")] protected theorem LTCmp.compareOfLessAndEq [LT α] [DecidableRel (LT.lt (α := α))] [DecidableEq α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (lt_antisymm : ∀ {x y : α}, ¬x < y → ¬y < x → x = y) : LTCmp (α := α) (compareOfLessAndEq · ·) := { TransCmp.compareOfLessAndEq lt_irrefl lt_trans lt_antisymm with cmp_iff_lt := compareOfLessAndEq_eq_lt } @[deprecated Std.LawfulLTCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (since := "2025-07-01")] protected theorem LTCmp.compareOfLessAndEq_of_le [LT α] [DecidableRel (LT.lt (α := α))] [DecidableEq α] [LE α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (not_lt : ∀ {x y : α}, ¬x < y → y ≤ x) (le_antisymm : ∀ {x y : α}, x ≤ y → y ≤ x → x = y) : LTCmp (α := α) (compareOfLessAndEq · ·) := { TransCmp.compareOfLessAndEq_of_le lt_irrefl lt_trans not_lt le_antisymm with cmp_iff_lt := compareOfLessAndEq_eq_lt } @[deprecated Std.LawfulLECmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (since := "2025-07-01")] protected theorem LECmp.compareOfLessAndEq [LT α] [DecidableRel (LT.lt (α := α))] [DecidableEq α] [LE α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (not_lt : ∀ {x y : α}, ¬x < y ↔ y ≤ x) (le_antisymm : ∀ {x y : α}, x ≤ y → y ≤ x → x = y) : LECmp (α := α) (compareOfLessAndEq · ·) := have := TransCmp.compareOfLessAndEq_of_le lt_irrefl lt_trans not_lt.1 le_antisymm { this with cmp_iff_le := (this.cmp_ne_gt).trans <| (not_congr compareOfLessAndEq_eq_lt).trans not_lt } @[deprecated Std.LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (since := "2025-07-01")] protected theorem LawfulCmp.compareOfLessAndEq [LT α] [DecidableRel (LT.lt (α := α))] [DecidableEq α] [BEq α] [LawfulBEq α] [LE α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (not_lt : ∀ {x y : α}, ¬x < y ↔ y ≤ x) (le_antisymm : ∀ {x y : α}, x ≤ y → y ≤ x → x = y) : LawfulCmp (α := α) (compareOfLessAndEq · ·) := { TransCmp.compareOfLessAndEq_of_le lt_irrefl lt_trans not_lt.1 le_antisymm, LTCmp.compareOfLessAndEq_of_le lt_irrefl lt_trans not_lt.1 le_antisymm, LECmp.compareOfLessAndEq lt_irrefl lt_trans not_lt le_antisymm, BEqCmp.compareOfLessAndEq lt_irrefl with } @[deprecated Std.LawfulLTCmp.eq_compareOfLessAndEq (since := "2025-07-01")] theorem LTCmp.eq_compareOfLessAndEq [LT α] [DecidableEq α] [BEq α] [LawfulBEq α] [BEqCmp cmp] [LTCmp cmp] (x y : α) [Decidable (x < y)] : cmp x y = compareOfLessAndEq x y := by simp [compareOfLessAndEq] split <;> rename_i h1 <;> [skip; split <;> rename_i h2] · exact LTCmp.cmp_iff_lt.2 h1 · exact BEqCmp.cmp_iff_eq.2 h2 · cases e : cmp x y · cases h1 (LTCmp.cmp_iff_lt.1 e) · cases h2 (BEqCmp.cmp_iff_eq.1 e) · rfl instance [inst₁ : OrientedCmp cmp₁] [inst₂ : OrientedCmp cmp₂] : OrientedCmp (compareLex cmp₁ cmp₂) where symm _ _ := by simp [compareLex, Ordering.swap_then]; rw [inst₁.symm, inst₂.symm] example [inst₁ : Std.OrientedCmp cmp₁] [inst₂ : Std.OrientedCmp cmp₂] : Std.OrientedCmp (compareLex cmp₁ cmp₂) := inferInstance instance [inst₁ : TransCmp cmp₁] [inst₂ : TransCmp cmp₂] : TransCmp (compareLex cmp₁ cmp₂) where le_trans {a b c} h1 h2 := by simp only [compareLex, ne_eq, Ordering.then_eq_gt, not_or, not_and] at h1 h2 ⊢ refine ⟨inst₁.le_trans h1.1 h2.1, fun e1 e2 => ?_⟩ match ab : cmp₁ a b with | .gt => exact h1.1 ab | .eq => exact inst₂.le_trans (h1.2 ab) (h2.2 (inst₁.cmp_congr_left ab ▸ e1)) e2 | .lt => exact h2.1 <| (inst₁.cmp_eq_gt).2 (inst₁.cmp_congr_left e1 ▸ ab) example [inst₁ : Std.TransCmp cmp₁] [inst₂ : Std.TransCmp cmp₂] : Std.TransCmp (compareLex cmp₁ cmp₂) := inferInstance instance [Ord β] [OrientedOrd β] (f : α → β) : OrientedCmp (compareOn f) where symm _ _ := OrientedCmp.symm (α := β) .. example [Ord β] [Std.OrientedOrd β] (f : α → β) : Std.OrientedCmp (compareOn f) := inferInstance instance [Ord β] [TransOrd β] (f : α → β) : TransCmp (compareOn f) where le_trans := TransCmp.le_trans (α := β) example [Ord β] [Std.TransOrd β] (f : α → β) : Std.TransCmp (compareOn f) := inferInstance section «non-canonical instances» -- Note: the following instances seem to cause lean to fail, see: -- https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Typeclass.20inference.20crashes/near/432836360 /-- Local instance for `OrientedOrd lexOrd`. -/ @[deprecated "instance exists" (since := "2025-07-01")] theorem OrientedOrd.instLexOrd [Ord α] [Ord β] [OrientedOrd α] [OrientedOrd β] : @OrientedOrd (α × β) lexOrd := by rw [OrientedOrd, lexOrd_def]; infer_instance /-- Local instance for `TransOrd lexOrd`. -/ @[deprecated "instance exists" (since := "2025-07-01")] theorem TransOrd.instLexOrd [Ord α] [Ord β] [TransOrd α] [TransOrd β] : @TransOrd (α × β) lexOrd := by rw [TransOrd, lexOrd_def]; infer_instance /-- Local instance for `OrientedOrd ord.opposite`. -/ @[deprecated Std.OrientedOrd.opposite (since := "2025-07-01")] theorem OrientedOrd.instOpposite [ord : Ord α] [inst : OrientedOrd α] : @OrientedOrd _ ord.opposite where symm _ _ := inst.symm .. /-- Local instance for `TransOrd ord.opposite`. -/ @[deprecated Std.TransOrd.opposite (since := "2025-07-01")] theorem TransOrd.instOpposite [ord : Ord α] [inst : TransOrd α] : @TransOrd _ ord.opposite := { OrientedOrd.instOpposite with le_trans := fun h1 h2 => inst.le_trans h2 h1 } /-- Local instance for `OrientedOrd (ord.on f)`. -/ @[deprecated Std.OrientedOrd.instOn (since := "2025-07-01")] theorem OrientedOrd.instOn [ord : Ord β] [OrientedOrd β] (f : α → β) : @OrientedOrd _ (ord.on f) := inferInstanceAs (@OrientedCmp _ (compareOn f)) /-- Local instance for `TransOrd (ord.on f)`. -/ @[deprecated Std.TransOrd.instOn (since := "2025-07-01")] theorem TransOrd.instOn [ord : Ord β] [TransOrd β] (f : α → β) : @TransOrd _ (ord.on f) := inferInstanceAs (@TransCmp _ (compareOn f)) /-- Local instance for `OrientedOrd (oα.lex oβ)`. -/ @[deprecated "instance exists" (since := "2025-07-01")] theorem OrientedOrd.instOrdLex [oα : Ord α] [oβ : Ord β] [OrientedOrd α] [OrientedOrd β] : @OrientedOrd _ (oα.lex oβ) := OrientedOrd.instLexOrd /-- Local instance for `TransOrd (oα.lex oβ)`. -/ @[deprecated "instance exists" (since := "2025-07-01")] theorem TransOrd.instOrdLex [oα : Ord α] [oβ : Ord β] [TransOrd α] [TransOrd β] : @TransOrd _ (oα.lex oβ) := TransOrd.instLexOrd /-- Local instance for `OrientedOrd (oα.lex' oβ)`. -/ @[deprecated Std.OrientedOrd.instOrdLex' (since := "2025-07-01")] theorem OrientedOrd.instOrdLex' (ord₁ ord₂ : Ord α) [@OrientedOrd _ ord₁] [@OrientedOrd _ ord₂] : @OrientedOrd _ (ord₁.lex' ord₂) := inferInstanceAs (OrientedCmp (compareLex ord₁.compare ord₂.compare)) /-- Local instance for `TransOrd (oα.lex' oβ)`. -/ @[deprecated Std.TransOrd.instOrdLex' (since := "2025-07-01")] theorem TransOrd.instOrdLex' (ord₁ ord₂ : Ord α) [@TransOrd _ ord₁] [@TransOrd _ ord₂] : @TransOrd _ (ord₁.lex' ord₂) := inferInstanceAs (TransCmp (compareLex ord₁.compare ord₂.compare)) end «non-canonical instances»
.lake/packages/batteries/Batteries/Classes/Order.lean
module public import Batteries.Tactic.Basic public import Batteries.Tactic.SeqFocus @[expose] public section theorem lexOrd_def [Ord α] [Ord β] : (lexOrd : Ord (α × β)).compare = compareLex (compareOn (·.1)) (compareOn (·.2)) := rfl /-- Pull back a comparator by a function `f`, by applying the comparator to both arguments. -/ @[inline] def Ordering.byKey (f : α → β) (cmp : β → β → Ordering) (a b : α) : Ordering := cmp (f a) (f b) namespace Batteries /-- `TotalBLE le` asserts that `le` has a total order, that is, `le a b ∨ le b a`. -/ class TotalBLE (le : α → α → Bool) : Prop where /-- `le` is total: either `le a b` or `le b a`. -/ total : le a b ∨ le b a theorem compareOfLessAndEq_eq_lt {x y : α} [LT α] [Decidable (x < y)] [DecidableEq α] : compareOfLessAndEq x y = .lt ↔ x < y := by simp [compareOfLessAndEq] split <;> simp end Batteries /-! Batteries features not in core Std -/ namespace Std open Batteries (compareOfLessAndEq_eq_lt) namespace OrientedCmp variable {cmp : α → α → Ordering} [OrientedCmp cmp] theorem le_iff_ge : cmp x y ≠ .gt ↔ cmp y x ≠ .lt := not_congr OrientedCmp.gt_iff_lt end OrientedCmp namespace TransCmp variable {cmp : α → α → Ordering} [TransCmp cmp] theorem le_trans : cmp x y ≠ .gt → cmp y z ≠ .gt → cmp x z ≠ .gt := by simp only [ne_eq, ← Ordering.isLE_iff_ne_gt]; exact isLE_trans theorem lt_of_lt_of_le : cmp x y = .lt → cmp y z ≠ .gt → cmp x z = .lt := by simp only [ne_eq, ← Ordering.isLE_iff_ne_gt]; exact lt_of_lt_of_isLE theorem lt_of_le_of_lt : cmp x y ≠ .gt → cmp y z = .lt → cmp x z = .lt := by simp only [ne_eq, ← Ordering.isLE_iff_ne_gt]; exact lt_of_isLE_of_lt theorem ge_trans : cmp x y ≠ .lt → cmp y z ≠ .lt → cmp x z ≠ .lt := by simp only [ne_eq, ← Ordering.isGE_iff_ne_lt]; exact isGE_trans theorem gt_of_gt_of_ge : cmp x y = .gt → cmp y z ≠ .lt → cmp x z = .gt := by simp only [ne_eq, ← Ordering.isGE_iff_ne_lt]; exact gt_of_gt_of_isGE theorem gt_of_ge_of_gt : cmp x y ≠ .lt → cmp y z = .gt → cmp x z = .gt := by simp only [ne_eq, ← Ordering.isGE_iff_ne_lt]; exact gt_of_isGE_of_gt end TransCmp /-- `LawfulLTCmp cmp` asserts that `cmp x y = .lt` and `x < y` coincide. -/ class LawfulLTCmp [LT α] (cmp : α → α → Ordering) : Prop extends OrientedCmp cmp where /-- `cmp x y = .lt` holds iff `x < y` is true. -/ eq_lt_iff_lt : cmp x y = .lt ↔ x < y theorem LawfulLTCmp.eq_gt_iff_gt [LT α] [LawfulLTCmp (α := α) cmp] : cmp x y = .gt ↔ y < x := by rw [OrientedCmp.gt_iff_lt, eq_lt_iff_lt] /-- `LawfulLECmp cmp` asserts that `(cmp x y).isLE` and `x ≤ y` coincide. -/ class LawfulLECmp [LE α] (cmp : α → α → Ordering) : Prop extends OrientedCmp cmp where /-- `cmp x y ≠ .gt` holds iff `x ≤ y` is true. -/ isLE_iff_le : (cmp x y).isLE ↔ x ≤ y theorem LawfulLECmp.isGE_iff_ge [LE α] [LawfulLECmp (α := α) cmp] : (cmp x y).isGE ↔ y ≤ x := by rw [← Ordering.isLE_swap, ← OrientedCmp.eq_swap, isLE_iff_le] theorem LawfulLECmp.ne_gt_iff_le [LE α] [LawfulLECmp (α := α) cmp] : cmp x y ≠ .gt ↔ x ≤ y := by rw [← isLE_iff_le (cmp := cmp), Ordering.isLE_iff_ne_gt] theorem LawfulLECmp.ne_lt_iff_ge [LE α] [LawfulLECmp (α := α) cmp] : cmp x y ≠ .lt ↔ y ≤ x := by rw [← isGE_iff_ge (cmp := cmp), Ordering.isGE_iff_ne_lt] /-- `LawfulBCmp cmp` asserts that the `LE`, `LT`, `BEq` are all coherent with each other and with `cmp`, describing a strict weak order (a linear order except for antisymmetry). -/ class LawfulBCmp [LE α] [LT α] [BEq α] (cmp : α → α → Ordering) : Prop extends TransCmp cmp, LawfulBEqCmp cmp, LawfulLTCmp cmp, LawfulLECmp cmp /-- `LawfulBCmp cmp` asserts that the `LE`, `LT`, `Eq` are all coherent with each other and with `cmp`, describing a linear order. -/ class LawfulCmp [LE α] [LT α] (cmp : α → α → Ordering) : Prop extends TransCmp cmp, LawfulEqCmp cmp, LawfulLTCmp cmp, LawfulLECmp cmp /-- Class for types where the ordering function is compatible with the `LT`. -/ abbrev LawfulLTOrd (α) [LT α] [Ord α] := LawfulLTCmp (α := α) compare /-- Class for types where the ordering function is compatible with the `LE`. -/ abbrev LawfulLEOrd (α) [LE α] [Ord α] := LawfulLECmp (α := α) compare /-- Class for types where the ordering function is compatible with the `LE`, `LT` and `BEq`. -/ abbrev LawfulBOrd (α) [LE α] [LT α] [BEq α] [Ord α] := LawfulBCmp (α := α) compare /-- Class for types where the ordering function is compatible with the `LE`, `LT` and `Eq`. -/ abbrev LawfulOrd (α) [LE α] [LT α] [Ord α] := LawfulCmp (α := α) compare instance [inst : Std.OrientedCmp cmp] : Std.OrientedCmp (flip cmp) where eq_swap := inst.eq_swap instance [inst : Std.TransCmp cmp] : Std.TransCmp (flip cmp) where isLE_trans h1 h2 := inst.isLE_trans h2 h1 instance (f : α → β) (cmp : β → β → Ordering) [Std.OrientedCmp cmp] : Std.OrientedCmp (Ordering.byKey f cmp) where eq_swap {a b} := Std.OrientedCmp.eq_swap (a := f a) (b := f b) instance (f : α → β) (cmp : β → β → Ordering) [Std.TransCmp cmp] : Std.TransCmp (Ordering.byKey f cmp) where isLE_trans h₁ h₂ := Std.TransCmp.isLE_trans (α := β) h₁ h₂ instance [inst₁ : OrientedCmp cmp₁] [inst₂ : OrientedCmp cmp₂] : OrientedCmp (compareLex cmp₁ cmp₂) := inferInstance instance [inst₁ : TransCmp cmp₁] [inst₂ : TransCmp cmp₂] : TransCmp (compareLex cmp₁ cmp₂) := inferInstance instance [Ord β] [OrientedOrd β] (f : α → β) : OrientedCmp (compareOn f) := inferInstance instance [Ord β] [TransOrd β] (f : α → β) : TransCmp (compareOn f) := inferInstance theorem OrientedOrd.instOn [ord : Ord β] [OrientedOrd β] (f : α → β) : @OrientedOrd _ (ord.on f) := inferInstanceAs (@OrientedCmp _ (compareOn f)) theorem TransOrd.instOn [ord : Ord β] [TransOrd β] (f : α → β) : @TransOrd _ (ord.on f) := inferInstanceAs (@TransCmp _ (compareOn f)) theorem OrientedOrd.instOrdLex' (ord₁ ord₂ : Ord α) [@OrientedOrd _ ord₁] [@OrientedOrd _ ord₂] : @OrientedOrd _ (ord₁.lex' ord₂) := inferInstanceAs (OrientedCmp (compareLex ord₁.compare ord₂.compare)) theorem TransOrd.instOrdLex' (ord₁ ord₂ : Ord α) [@TransOrd _ ord₁] [@TransOrd _ ord₂] : @TransOrd _ (ord₁.lex' ord₂) := inferInstanceAs (TransCmp (compareLex ord₁.compare ord₂.compare)) theorem LawfulLTCmp.eq_compareOfLessAndEq [LT α] [DecidableEq α] [LawfulEqCmp cmp] [LawfulLTCmp cmp] (x y : α) [Decidable (x < y)] : cmp x y = compareOfLessAndEq x y := by simp only [compareOfLessAndEq] split <;> rename_i h1 <;> [skip; split <;> rename_i h2] · exact LawfulLTCmp.eq_lt_iff_lt.2 h1 · exact LawfulEqCmp.compare_eq_iff_eq.2 h2 · cases e : cmp x y · cases h1 (LawfulLTCmp.eq_lt_iff_lt.1 e) · cases h2 (LawfulEqCmp.compare_eq_iff_eq.1 e) · rfl theorem ReflCmp.compareOfLessAndEq_of_lt_irrefl [LT α] [DecidableLT α] [DecidableEq α] (lt_irrefl : ∀ x : α, ¬ x < x) : ReflCmp (α := α) (compareOfLessAndEq · ·) where compare_self {x} := by simp [compareOfLessAndEq, if_neg (lt_irrefl x)] theorem LawfulBEqCmp.compareOfLessAndEq_of_lt_irrefl [LT α] [DecidableLT α] [DecidableEq α] [BEq α] [LawfulBEq α] (lt_irrefl : ∀ x : α, ¬x < x) : LawfulBEqCmp (α := α) (compareOfLessAndEq · ·) where compare_eq_iff_beq {x y} := by simp [compareOfLessAndEq] split <;> [skip; split] <;> simp [*] rintro rfl; exact lt_irrefl _ ‹_› -- redundant? See `compareOfLessAndEq_of_lt_trans_of_lt_iff` in core theorem TransCmp.compareOfLessAndEq_of_irrefl_of_trans_of_antisymm [LT α] [DecidableLT α] [DecidableEq α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (lt_antisymm : ∀ {x y : α}, ¬x < y → ¬y < x → x = y) : TransCmp (α := α) (compareOfLessAndEq · ·) := TransOrd.compareOfLessAndEq_of_lt_trans_of_lt_iff lt_trans <| by intros constructor · intro h₁ constructor · intro h₂ apply lt_irrefl exact lt_trans h₁ h₂ · intro | rfl => exact lt_irrefl _ h₁ · intro ⟨h₁, h₂⟩ by_contra h₃ apply h₂ exact lt_antisymm h₃ h₁ -- redundant? See `compareOfLessAndEq_of_antisymm_of_trans_of_total_of_not_le` in core theorem TransCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm [LT α] [LE α] [DecidableLT α] [DecidableEq α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (not_lt : ∀ {x y : α}, ¬x < y → y ≤ x) (le_antisymm : ∀ {x y : α}, x ≤ y → y ≤ x → x = y) : TransCmp (α := α) (compareOfLessAndEq · ·) := .compareOfLessAndEq_of_irrefl_of_trans_of_antisymm lt_irrefl lt_trans fun xy yx => le_antisymm (not_lt yx) (not_lt xy) -- make redundant? theorem LawfulLTCmp.compareOfLessAndEq_of_irrefl_of_trans_of_antisymm [LT α] [DecidableLT α] [DecidableEq α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (lt_antisymm : ∀ {x y : α}, ¬x < y → ¬y < x → x = y) : LawfulLTCmp (α := α) (compareOfLessAndEq · ·) := { TransCmp.compareOfLessAndEq_of_irrefl_of_trans_of_antisymm lt_irrefl lt_trans lt_antisymm with eq_lt_iff_lt := Batteries.compareOfLessAndEq_eq_lt } -- make redundant? theorem LawfulLTCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm [LT α] [DecidableLT α] [DecidableEq α] [LE α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (not_lt : ∀ {x y : α}, ¬x < y → y ≤ x) (le_antisymm : ∀ {x y : α}, x ≤ y → y ≤ x → x = y) : LawfulLTCmp (α := α) (compareOfLessAndEq · ·) := { TransCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm lt_irrefl lt_trans not_lt le_antisymm with eq_lt_iff_lt := Batteries.compareOfLessAndEq_eq_lt } -- make redundant? theorem LawfulLECmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm [LT α] [DecidableLT α] [DecidableEq α] [LE α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (not_lt : ∀ {x y : α}, ¬x < y ↔ y ≤ x) (le_antisymm : ∀ {x y : α}, x ≤ y → y ≤ x → x = y) : LawfulLECmp (α := α) (compareOfLessAndEq · ·) := have := TransCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm lt_irrefl lt_trans not_lt.1 le_antisymm { this with isLE_iff_le := by intro x y simp only [Ordering.isLE_iff_ne_gt, ← not_lt] apply not_congr rw [this.gt_iff_lt, Batteries.compareOfLessAndEq_eq_lt] } theorem LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm [LT α] [LE α] [DecidableLT α] [DecidableLE α] [DecidableEq α] (lt_irrefl : ∀ x : α, ¬x < x) (lt_trans : ∀ {x y z : α}, x < y → y < z → x < z) (not_lt : ∀ {x y : α}, ¬x < y ↔ y ≤ x) (le_antisymm : ∀ {x y : α}, x ≤ y → y ≤ x → x = y) : LawfulCmp (α := α) (compareOfLessAndEq · ·) := have instT := TransCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm lt_irrefl lt_trans not_lt.1 le_antisymm have instLT := LawfulLTCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm lt_irrefl lt_trans not_lt.1 le_antisymm have instLE := LawfulLECmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm lt_irrefl lt_trans not_lt le_antisymm have le_refl (x : α) : x ≤ x := by rw [← not_lt]; exact lt_irrefl _ have not_le {x y : α} : ¬x ≤ y ↔ y < x := by simp [← not_lt] { instT, instLT, instLE with eq_of_compare {_ _}:= by rw [compareOfLessAndEq_eq_eq le_refl not_le]; exact id } instance : LawfulOrd Nat := LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm Nat.lt_irrefl Nat.lt_trans Nat.not_lt Nat.le_antisymm instance : LawfulOrd Int := LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm Int.lt_irrefl Int.lt_trans Int.not_lt Int.le_antisymm instance : LawfulOrd Bool := by apply LawfulCmp.mk <;> decide instance : LawfulOrd (Fin n) where eq_swap := OrientedCmp.eq_swap (α := Nat) (cmp := compare) .. eq_lt_iff_lt := LawfulLTCmp.eq_lt_iff_lt (α := Nat) (cmp := compare) isLE_iff_le := LawfulLECmp.isLE_iff_le (α := Nat) (cmp := compare) isLE_trans := TransCmp.isLE_trans (α := Nat) (cmp := compare) end Std
.lake/packages/batteries/Batteries/Classes/SatisfiesM.lean
module public import Batteries.Lean.EStateM public import Batteries.Lean.Except @[expose] public section /-! ## SatisfiesM The `SatisfiesM` predicate works over an arbitrary (lawful) monad / applicative / functor, and enables Hoare-like reasoning over monadic expressions. For example, given a monadic function `f : α → m β`, to say that the return value of `f` satisfies `Q` whenever the input satisfies `P`, we write `∀ a, P a → SatisfiesM Q (f a)`. For any monad equipped with `MonadSatisfying m` one can lift `SatisfiesM` to a monadic value in `Subtype`, using `satisfying x h : m {a // p a}`, where `x : m α` and `h : SatisfiesM p x`. This includes `Option`, `ReaderT`, `StateT`, and `ExceptT`, and the Lean monad stack. (Although it is not entirely clear one should treat the Lean monad stack as lawful, even though Lean accepts this.) ## Notes `SatisfiesM` is not yet a satisfactory solution for verifying the behaviour of large scale monadic programs. Such a solution would allow ergonomic reasoning about large `do` blocks, with convenient mechanisms for introducing invariants and loop conditions as needed. It is possible that in the future `SatiesfiesM` will become part of such a solution, presumably requiring more syntactic support (and smarter `do` blocks) from Lean. Or it may be that such a solution will look different! This is an open research program, and for now one should not be overly ambitious using `SatisfiesM`. In particular lemmas about pure operations on data structures in `Batteries` except for `HashMap` should avoid `SatisfiesM` for now, so that it is easy to migrate to other approaches in future. -/ /-- `SatisfiesM p (x : m α)` lifts propositions over a monad. It asserts that `x` may as well have the type `x : m {a // p a}`, because there exists some `m {a // p a}` whose image is `x`. So `p` is the postcondition of the monadic value. -/ def SatisfiesM {m : Type u → Type v} [Functor m] (p : α → Prop) (x : m α) : Prop := ∃ x' : m {a // p a}, Subtype.val <$> x' = x namespace SatisfiesM /-- If `p` is always true, then every `x` satisfies it. -/ theorem of_true [Functor m] [LawfulFunctor m] {x : m α} (h : ∀ a, p a) : SatisfiesM p x := ⟨(fun a => ⟨a, h a⟩) <$> x, by simp⟩ /-- If `p` is always true, then every `x` satisfies it. (This is the strongest postcondition version of `of_true`.) -/ protected theorem trivial [Functor m] [LawfulFunctor m] {x : m α} : SatisfiesM (fun _ => True) x := of_true fun _ => trivial /-- The `SatisfiesM p x` predicate is monotonic in `p`. -/ theorem imp [Functor m] [LawfulFunctor m] {x : m α} (h : SatisfiesM p x) (H : ∀ {a}, p a → q a) : SatisfiesM q x := let ⟨x, h⟩ := h; ⟨(fun ⟨_, h⟩ => ⟨_, H h⟩) <$> x, by rw [← h, ← comp_map]; rfl⟩ /-- `SatisfiesM` distributes over `<$>`, general version. -/ protected theorem map [Functor m] [LawfulFunctor m] {x : m α} (hx : SatisfiesM p x) (hf : ∀ {a}, p a → q (f a)) : SatisfiesM q (f <$> x) := by let ⟨x', hx⟩ := hx refine ⟨(fun ⟨a, h⟩ => ⟨f a, hf h⟩) <$> x', ?_⟩ rw [← hx]; simp /-- `SatisfiesM` distributes over `<$>`, strongest postcondition version. (Use this for reasoning forward from assumptions.) -/ theorem map_post [Functor m] [LawfulFunctor m] {x : m α} (hx : SatisfiesM p x) : SatisfiesM (fun b => ∃ a, p a ∧ b = f a) (f <$> x) := hx.map fun h => ⟨_, h, rfl⟩ /-- `SatisfiesM` distributes over `<$>`, weakest precondition version. (Use this for reasoning backward from the goal.) -/ theorem map_pre [Functor m] [LawfulFunctor m] {x : m α} (hx : SatisfiesM (fun a => p (f a)) x) : SatisfiesM p (f <$> x) := hx.map fun h => h /-- `SatisfiesM` distributes over `mapConst`, general version. -/ protected theorem mapConst [Functor m] [LawfulFunctor m] {x : m α} (hx : SatisfiesM q x) (ha : ∀ {b}, q b → p a) : SatisfiesM p (Functor.mapConst a x) := map_const (f := m) ▸ hx.map ha /-- `SatisfiesM` distributes over `pure`, general version / weakest precondition version. -/ protected theorem pure [Applicative m] [LawfulApplicative m] (h : p a) : SatisfiesM (m := m) p (pure a) := ⟨pure ⟨_, h⟩, by simp⟩ /-- `SatisfiesM` distributes over `<*>`, general version. -/ protected theorem seq [Applicative m] [LawfulApplicative m] {x : m α} (hf : SatisfiesM p₁ f) (hx : SatisfiesM p₂ x) (H : ∀ {f a}, p₁ f → p₂ a → q (f a)) : SatisfiesM q (f <*> x) := by match f, x, hf, hx with | _, _, ⟨f, rfl⟩, ⟨x, rfl⟩ => ?_ refine ⟨(fun ⟨a, h₁⟩ ⟨b, h₂⟩ => ⟨a b, H h₁ h₂⟩) <$> f <*> x, ?_⟩ simp only [← pure_seq]; simp [seq_assoc] simp only [← pure_seq]; simp [seq_assoc, Function.comp_def] /-- `SatisfiesM` distributes over `<*>`, strongest postcondition version. -/ protected theorem seq_post [Applicative m] [LawfulApplicative m] {x : m α} (hf : SatisfiesM p₁ f) (hx : SatisfiesM p₂ x) : SatisfiesM (fun c => ∃ f a, p₁ f ∧ p₂ a ∧ c = f a) (f <*> x) := hf.seq hx fun hf ha => ⟨_, _, hf, ha, rfl⟩ /-- `SatisfiesM` distributes over `<*>`, weakest precondition version 1. (Use this when `x` and the goal are known and `f` is a subgoal.) -/ protected theorem seq_pre [Applicative m] [LawfulApplicative m] {x : m α} (hf : SatisfiesM (fun f => ∀ {a}, p₂ a → q (f a)) f) (hx : SatisfiesM p₂ x) : SatisfiesM q (f <*> x) := hf.seq hx fun hf ha => hf ha /-- `SatisfiesM` distributes over `<*>`, weakest precondition version 2. (Use this when `f` and the goal are known and `x` is a subgoal.) -/ protected theorem seq_pre' [Applicative m] [LawfulApplicative m] {x : m α} (hf : SatisfiesM p₁ f) (hx : SatisfiesM (fun a => ∀ {f}, p₁ f → q (f a)) x) : SatisfiesM q (f <*> x) := hf.seq hx fun hf ha => ha hf /-- `SatisfiesM` distributes over `<*`, general version. -/ protected theorem seqLeft [Applicative m] [LawfulApplicative m] {x : m α} (hx : SatisfiesM p₁ x) (hy : SatisfiesM p₂ y) (H : ∀ {a b}, p₁ a → p₂ b → q a) : SatisfiesM q (x <* y) := seqLeft_eq x y ▸ (hx.map fun h _ => H h).seq_pre hy /-- `SatisfiesM` distributes over `*>`, general version. -/ protected theorem seqRight [Applicative m] [LawfulApplicative m] {x : m α} (hx : SatisfiesM p₁ x) (hy : SatisfiesM p₂ y) (H : ∀ {a b}, p₁ a → p₂ b → q b) : SatisfiesM q (x *> y) := seqRight_eq x y ▸ (hx.map fun h _ => H h).seq_pre hy /-- `SatisfiesM` distributes over `>>=`, general version. -/ protected theorem bind [Monad m] [LawfulMonad m] {f : α → m β} (hx : SatisfiesM p x) (hf : ∀ a, p a → SatisfiesM q (f a)) : SatisfiesM q (x >>= f) := by match x, hx with | _, ⟨x, rfl⟩ => ?_ have g a ha := Classical.indefiniteDescription _ (hf a ha) refine ⟨x >>= fun ⟨a, h⟩ => g a h, ?_⟩ simp [← bind_pure_comp]; congr; funext ⟨a, h⟩; simp [← (g a h).2, ← bind_pure_comp] /-- `SatisfiesM` distributes over `>>=`, weakest precondition version. -/ protected theorem bind_pre [Monad m] [LawfulMonad m] {f : α → m β} (hx : SatisfiesM (fun a => SatisfiesM q (f a)) x) : SatisfiesM q (x >>= f) := hx.bind fun _ h => h end SatisfiesM @[simp] theorem SatisfiesM_Id_eq : SatisfiesM (m := Id) p x ↔ p x := ⟨fun ⟨y, eq⟩ => eq ▸ y.2, fun h => ⟨⟨_, h⟩, rfl⟩⟩ @[simp] theorem SatisfiesM_Option_eq : SatisfiesM (m := Option) p x ↔ ∀ a, x = some a → p a := ⟨by revert x; intro | some _, ⟨some ⟨_, h⟩, rfl⟩, _, rfl => exact h, fun h => match x with | some a => ⟨some ⟨a, h _ rfl⟩, rfl⟩ | none => ⟨none, rfl⟩⟩ @[simp] theorem SatisfiesM_Except_eq : SatisfiesM (m := Except ε) p x ↔ ∀ a, x = .ok a → p a := ⟨by revert x; intro | .ok _, ⟨.ok ⟨_, h⟩, rfl⟩, _, rfl => exact h, fun h => match x with | .ok a => ⟨.ok ⟨a, h _ rfl⟩, rfl⟩ | .error e => ⟨.error e, rfl⟩⟩ theorem SatisfiesM_EStateM_eq : SatisfiesM (m := EStateM ε σ) p x ↔ ∀ s a s', x.run s = .ok a s' → p a := by constructor · rintro ⟨x, rfl⟩ s a s' h match w : x.run s with | .ok a s' => simp at h; exact h.1 | .error e s' => simp [w] at h · intro w refine ⟨?_, ?_⟩ · intro s match q : x.run s with | .ok a s' => exact .ok ⟨a, w s a s' q⟩ s' | .error e s' => exact .error e s' · ext s rw [EStateM.run_map, EStateM.run] split <;> simp_all theorem SatisfiesM_ReaderT_eq [Monad m] : SatisfiesM (m := ReaderT ρ m) p x ↔ ∀ s, SatisfiesM p (x.run s) := (exists_congr fun a => by exact ⟨fun eq _ => eq ▸ rfl, funext⟩).trans Classical.skolem.symm theorem SatisfiesM_StateRefT_eq [Monad m] : SatisfiesM (m := StateRefT' ω σ m) p x ↔ ∀ s, SatisfiesM p (x s) := by simp [SatisfiesM_ReaderT_eq, ReaderT.run] theorem SatisfiesM_StateT_eq [Monad m] [LawfulMonad m] : SatisfiesM (m := StateT ρ m) (α := α) p x ↔ ∀ s, SatisfiesM (m := m) (p ·.1) (x.run s) := by change SatisfiesM (m := StateT ρ m) (α := α) p x ↔ ∀ s, SatisfiesM (m := m) (p ·.1) (x s) refine .trans ⟨fun ⟨f, eq⟩ => eq ▸ ?_, fun ⟨f, h⟩ => ?_⟩ Classical.skolem.symm · refine ⟨fun s => (fun ⟨⟨a, h⟩, s'⟩ => ⟨⟨a, s'⟩, h⟩) <$> f s, fun s => ?_⟩ rw [← comp_map, map_eq_pure_bind]; rfl · refine ⟨fun s => (fun ⟨⟨a, s'⟩, h⟩ => ⟨⟨a, h⟩, s'⟩) <$> f s, funext fun s => ?_⟩ show _ >>= _ = _; simp [← h] theorem SatisfiesM_ExceptT_eq [Monad m] [LawfulMonad m] : SatisfiesM (m := ExceptT ρ m) (α := α) p x ↔ SatisfiesM (m := m) (∀ a, · = .ok a → p a) x.run := by change _ ↔ SatisfiesM (m := m) (∀ a, · = .ok a → p a) x refine ⟨fun ⟨f, eq⟩ => eq ▸ ?_, fun ⟨f, eq⟩ => eq ▸ ?_⟩ · exists (fun | .ok ⟨a, h⟩ => ⟨.ok a, fun | _, rfl => h⟩ | .error e => ⟨.error e, nofun⟩) <$> f show _ = _ >>= _; rw [← comp_map, map_eq_pure_bind]; congr; funext a; cases a <;> rfl · exists ((fun | ⟨.ok a, h⟩ => .ok ⟨a, h _ rfl⟩ | ⟨.error e, _⟩ => .error e) <$> f : m _) show _ >>= _ = _; simp [← bind_pure_comp]; congr; funext ⟨a, h⟩; cases a <;> rfl /-- If a monad has `MonadSatisfying m`, then we can lift a `h : SatisfiesM (m := m) p x` predicate to monadic value `satisfying x p : m { x // p x }`. Reader, state, and exception monads have `MonadSatisfying` instances if the base monad does. -/ class MonadSatisfying (m : Type u → Type v) [Functor m] [LawfulFunctor m] where /-- Lift a `SatisfiesM` predicate to a monadic value. -/ satisfying {p : α → Prop} {x : m α} (h : SatisfiesM (m := m) p x) : m {a // p a} /-- The value of the lifted monadic value is equal to the original monadic value. -/ val_eq {p : α → Prop} {x : m α} (h : SatisfiesM (m := m) p x) : Subtype.val <$> satisfying h = x export MonadSatisfying (satisfying) namespace MonadSatisfying instance : MonadSatisfying Id where satisfying {α p x} h := ⟨x, by obtain ⟨⟨_, h⟩, rfl⟩ := h; exact h⟩ val_eq {α p x} h := rfl instance : MonadSatisfying Option where satisfying {α p x?} h := have h' := SatisfiesM_Option_eq.mp h match x? with | none => none | some x => some ⟨x, h' x rfl⟩ val_eq {α p x?} h := by cases x? <;> simp instance : MonadSatisfying (Except ε) where satisfying {α p x?} h := have h' := SatisfiesM_Except_eq.mp h match x? with | .ok x => .ok ⟨x, h' x rfl⟩ | .error e => .error e val_eq {α p x?} h := by cases x? <;> simp instance [Monad m] [LawfulMonad m][MonadSatisfying m] : MonadSatisfying (ReaderT ρ m) where satisfying {α p x} h := have h' := SatisfiesM_ReaderT_eq.mp h fun r => satisfying (h' r) val_eq {α p x} h := by have h' := SatisfiesM_ReaderT_eq.mp h ext r rw [ReaderT.run_map, ← MonadSatisfying.val_eq (h' r)] rfl instance [Monad m] [LawfulMonad m] [MonadSatisfying m] : MonadSatisfying (StateRefT' ω σ m) := inferInstanceAs <| MonadSatisfying (ReaderT _ _) instance [Monad m] [LawfulMonad m] [MonadSatisfying m] : MonadSatisfying (StateT ρ m) where satisfying {α p x} h := have h' := SatisfiesM_StateT_eq.mp h fun r => (fun ⟨⟨a, r'⟩, h⟩ => ⟨⟨a, h⟩, r'⟩) <$> satisfying (h' r) val_eq {α p x} h := by have h' := SatisfiesM_StateT_eq.mp h ext r rw [← MonadSatisfying.val_eq (h' r), StateT.run_map] simp [StateT.run] instance [Monad m] [LawfulMonad m] [MonadSatisfying m] : MonadSatisfying (ExceptT ε m) where satisfying {α p x} h := let x' := satisfying (SatisfiesM_ExceptT_eq.mp h) ExceptT.mk ((fun ⟨y, w⟩ => y.pmap fun a h => ⟨a, w _ h⟩) <$> x') val_eq {α p x} h := by ext refine Eq.trans ?_ (MonadSatisfying.val_eq (SatisfiesM_ExceptT_eq.mp h)) simp instance : MonadSatisfying (EStateM ε σ) where satisfying {α p x} h := have h' := SatisfiesM_EStateM_eq.mp h fun s => match w : x.run s with | .ok a s' => .ok ⟨a, h' s a s' w⟩ s' | .error e s' => .error e s' val_eq {α p x} h := by ext s rw [EStateM.run_map, EStateM.run] split <;> simp_all end MonadSatisfying
.lake/packages/batteries/Batteries/Classes/RatCast.lean
module @[expose] public section /-- Type class for the canonical homomorphism `Rat → K`. -/ class RatCast (K : Type u) where /-- The canonical homomorphism `Rat → K`. -/ protected ratCast : Rat → K instance : RatCast Rat where ratCast n := n /-- Canonical homomorphism from `Rat` to a division ring `K`. This is just the bare function in order to aid in creating instances of `DivisionRing`. -/ @[coe, reducible, match_pattern] protected def Rat.cast {K : Type u} [RatCast K] : Rat → K := RatCast.ratCast -- see note [coercion into rings] instance [RatCast K] : CoeTail Rat K where coe := Rat.cast -- see note [coercion into rings] instance [RatCast K] : CoeHTCT Rat K where coe := Rat.cast
.lake/packages/batteries/Batteries/Classes/Cast.lean
module public import Batteries.Util.LibraryNote @[expose] public section library_note "coercion into rings" /-- Coercions such as `Nat.castCoe` that go from a concrete structure such as `Nat` to an arbitrary ring `R` should be set up as follows: ```lean instance : CoeTail Nat R where coe := ... instance : CoeHTCT Nat R where coe := ... ``` It needs to be `CoeTail` instead of `Coe` because otherwise type-class inference would loop when constructing the transitive coercion `Nat → Nat → Nat → ...`. Sometimes we also need to declare the `CoeHTCT` instance if we need to shadow another coercion (e.g. `Nat.cast` should be used over `Int.ofNat`). -/
.lake/packages/batteries/Batteries/CodeAction/Deprecated.lean
module public meta import Lean.Server.CodeActions.Provider public meta section /-! # Code action for @[deprecated] replacements This is an opt-in mechanism for making machine-applicable `@[deprecated]` definitions. When enabled (by setting the `machineApplicableDeprecated` tag attribute), a code action will be triggered whenever the deprecation lint also fires, allowing the user to replace the usage of the deprecated constant. -/ namespace Batteries open Lean Elab Server Lsp RequestM CodeAction /-- An environment extension for identifying `@[deprecated]` definitions which can be auto-fixed -/ initialize machineApplicableDeprecated : TagDeclarationExtension ← mkTagDeclarationExtension namespace CodeAction /-- A code action which applies replacements for `@[deprecated]` definitions. -/ @[code_action_provider] def deprecatedCodeActionProvider : CodeActionProvider := fun params snap => do let mut i := 0 let doc ← readDoc let mut msgs := #[] for m in snap.msgLog.toList do if m.data.isDeprecationWarning then if h : _ then msgs := msgs.push (snap.cmdState.messages.toList[i]'h) i := i + 1 if msgs.isEmpty then return #[] let start := doc.meta.text.lspPosToUtf8Pos params.range.start let stop := doc.meta.text.lspPosToUtf8Pos params.range.end for msg in msgs do let some endPos := msg.endPos | continue let pos := doc.meta.text.ofPosition msg.pos let endPos' := doc.meta.text.ofPosition endPos unless start ≤ endPos' && pos ≤ stop do continue let some (ctx, .node (.ofTermInfo info@{ expr := .const c .., ..}) _) := findInfoTree? identKind ⟨pos, endPos'⟩ none snap.infoTree fun _ i => (i matches .ofTermInfo { elaborator := .anonymous, expr := .const .., ..}) | continue unless machineApplicableDeprecated.isTagged snap.cmdState.env c do continue let some c' := Linter.getDeprecatedNewName snap.cmdState.env c | continue let eager : CodeAction := { title := s!"Replace {c} with {c'}" kind? := "quickfix" isPreferred? := true } return #[{ eager lazy? := some do let c' ← info.runMetaM ctx (unresolveNameGlobal c') let pos := doc.meta.text.leanPosToLspPos msg.pos let endPos' := doc.meta.text.leanPosToLspPos endPos pure { eager with edit? := some <| .ofTextEdit doc.versionedIdentifier { range := ⟨pos, endPos'⟩ newText := toString c' } } }] return #[]
.lake/packages/batteries/Batteries/CodeAction/Attr.lean
module public import Lean.Server.CodeActions.Basic public import Lean.Compiler.IR.CompilerM @[expose] public section /-! # Initial setup for code action attributes * `@[hole_code_action]` and `@[command_code_action]` now live in the Lean repository, and are builtin. * Attribute `@[tactic_code_action]` collects code actions which will be called on each occurrence of a tactic. -/ namespace Batteries.CodeAction open Lean Elab Server Lsp RequestM Snapshots /-- A tactic code action extension. -/ abbrev TacticCodeAction := CodeActionParams → Snapshot → (ctx : ContextInfo) → (stack : Syntax.Stack) → (node : InfoTree) → RequestM (Array LazyCodeAction) /-- A tactic code action extension. -/ abbrev TacticSeqCodeAction := CodeActionParams → Snapshot → (ctx : ContextInfo) → (i : Nat) → (stack : Syntax.Stack) → (goals : List MVarId) → RequestM (Array LazyCodeAction) /-- Read a tactic code action from a declaration of the right type. -/ def mkTacticCodeAction (n : Name) : ImportM TacticCodeAction := do let { env, opts, .. } ← read IO.ofExcept <| unsafe env.evalConstCheck TacticCodeAction opts ``TacticCodeAction n /-- Read a tacticSeq code action from a declaration of the right type. -/ def mkTacticSeqCodeAction (n : Name) : ImportM TacticSeqCodeAction := do let { env, opts, .. } ← read IO.ofExcept <| unsafe env.evalConstCheck TacticSeqCodeAction opts ``TacticSeqCodeAction n /-- An entry in the tactic code actions extension, containing the attribute arguments. -/ structure TacticCodeActionEntry where /-- The declaration to tag -/ declName : Name /-- The tactic kinds that this extension supports. If empty it is called on all tactic kinds. -/ tacticKinds : Array Name deriving Inhabited /-- The state of the tactic code actions extension. -/ structure TacticCodeActions where /-- The list of tactic code actions to apply on any tactic. -/ onAnyTactic : Array TacticCodeAction := {} /-- The list of tactic code actions to apply when a particular tactic kind is highlighted. -/ onTactic : NameMap (Array TacticCodeAction) := {} deriving Inhabited /-- Insert a tactic code action entry into the `TacticCodeActions` structure. -/ def TacticCodeActions.insert (self : TacticCodeActions) (tacticKinds : Array Name) (action : TacticCodeAction) : TacticCodeActions := if tacticKinds.isEmpty then { self with onAnyTactic := self.onAnyTactic.push action } else { self with onTactic := tacticKinds.foldl (init := self.onTactic) fun m a => m.insert a ((m.getD a #[]).push action) } /-- An extension which collects all the tactic code actions. -/ initialize tacticSeqCodeActionExt : PersistentEnvExtension Name (Name × TacticSeqCodeAction) (Array Name × Array TacticSeqCodeAction) ← registerPersistentEnvExtension { mkInitial := pure (#[], #[]) addImportedFn := fun as => return (#[], ← as.foldlM (init := #[]) fun m as => as.foldlM (init := m) fun m a => return m.push (← mkTacticSeqCodeAction a)) addEntryFn := fun (s₁, s₂) (n₁, n₂) => (s₁.push n₁, s₂.push n₂) exportEntriesFn := (·.1) } /-- An extension which collects all the tactic code actions. -/ initialize tacticCodeActionExt : PersistentEnvExtension TacticCodeActionEntry (TacticCodeActionEntry × TacticCodeAction) (Array TacticCodeActionEntry × TacticCodeActions) ← registerPersistentEnvExtension { mkInitial := pure (#[], {}) addImportedFn := fun as => return (#[], ← as.foldlM (init := {}) fun m as => as.foldlM (init := m) fun m ⟨name, kinds⟩ => return m.insert kinds (← mkTacticCodeAction name)) addEntryFn := fun (s₁, s₂) (e, n₂) => (s₁.push e, s₂.insert e.tacticKinds n₂) exportEntriesFn := (·.1) } /-- This attribute marks a code action, which is used to suggest new tactics or replace existing ones. * `@[tactic_code_action]`: This is a code action which applies to the spaces between tactics, to suggest a new tactic to change the goal state. * `@[tactic_code_action kind]`: This is a code action which applies to applications of the tactic `kind` (a tactic syntax kind), which can replace the tactic or insert things before or after it. * `@[tactic_code_action kind₁ kind₂]`: shorthand for `@[tactic_code_action kind₁, tactic_code_action kind₂]`. * `@[tactic_code_action *]`: This is a tactic code action that applies to all tactics. Use sparingly. -/ syntax (name := tactic_code_action) "tactic_code_action" ("*" <|> (ppSpace ident)*) : attr initialize registerBuiltinAttribute { name := `tactic_code_action descr := "Declare a new tactic code action, to appear in the code actions on tactics" applicationTime := .afterCompilation add := fun decl stx kind => do unless kind == AttributeKind.global do throwError "invalid attribute 'tactic_code_action', must be global" match stx with | `(attr| tactic_code_action *) => if (IR.getSorryDep (← getEnv) decl).isSome then return -- ignore in progress definitions modifyEnv (tacticCodeActionExt.addEntry · (⟨decl, #[]⟩, ← mkTacticCodeAction decl)) | `(attr| tactic_code_action $[$args]*) => if args.isEmpty then if (IR.getSorryDep (← getEnv) decl).isSome then return -- ignore in progress definitions modifyEnv (tacticSeqCodeActionExt.addEntry · (decl, ← mkTacticSeqCodeAction decl)) else let args ← args.mapM realizeGlobalConstNoOverloadWithInfo if (IR.getSorryDep (← getEnv) decl).isSome then return -- ignore in progress definitions modifyEnv (tacticCodeActionExt.addEntry · (⟨decl, args⟩, ← mkTacticCodeAction decl)) | _ => pure () }
.lake/packages/batteries/Batteries/CodeAction/Basic.lean
module public meta import Lean.Elab.BuiltinTerm public meta import Lean.Elab.BuiltinNotation public meta import Lean.Server.InfoUtils public meta import Lean.Server.CodeActions.Provider public meta import Batteries.CodeAction.Attr public meta section /-! # Initial setup for code actions This declares a code action provider that calls all `@[hole_code_action]` definitions on each occurrence of a hole (`_`, `?_` or `sorry`). (This is in a separate file from `Batteries.CodeAction.Hole.Attr` so that the server does not attempt to use this code action provider when browsing the `Batteries.CodeAction.Hole.Attr` file itself.) -/ namespace Batteries.CodeAction open Lean Elab Server RequestM CodeAction /-- A code action which calls `@[tactic_code_action]` code actions. -/ @[code_action_provider] def tacticCodeActionProvider : CodeActionProvider := fun params snap => do let doc ← readDoc let startPos := doc.meta.text.lspPosToUtf8Pos params.range.start let endPos := doc.meta.text.lspPosToUtf8Pos params.range.end let pointerCol := if params.range.start.line == params.range.end.line then max params.range.start.character params.range.end.character else 0 let some result := findTactic? (fun pos => (doc.meta.text.utf8PosToLspPos pos).character ≤ pointerCol) ⟨startPos, endPos⟩ snap.stx | return #[] let tgtTac := match result with | .tactic (tac :: _) | .tacticSeq _ _ (_ :: tac :: _) => tac.1 | _ => unreachable! let tgtRange := tgtTac.getRange?.get! have info := findInfoTree? tgtTac.getKind tgtRange none snap.infoTree (canonicalOnly := true) fun _ info => info matches .ofTacticInfo _ let some (ctx, node@(.node (.ofTacticInfo info) _)) := info | return #[] let mut out := #[] match result with | .tactic stk@((tac, _) :: _) => do let ctx := { ctx with mctx := info.mctxBefore } let actions := (tacticCodeActionExt.getState snap.env).2 if let some arr := actions.onTactic.find? tac.getKind then for act in arr do try out := out ++ (← act params snap ctx stk node) catch _ => pure () for act in actions.onAnyTactic do try out := out ++ (← act params snap ctx stk node) catch _ => pure () | .tacticSeq _ i stk@((seq, _) :: _) => let (ctx, goals) ← if 2*i < seq.getNumArgs then let stx := seq[2*i] let some stxRange := stx.getRange? | return #[] let some (ctx, .node (.ofTacticInfo info') _) := findInfoTree? stx.getKind stxRange ctx node fun _ info => (info matches .ofTacticInfo _) | return #[] pure ({ ctx with mctx := info'.mctxBefore }, info'.goalsBefore) else pure ({ ctx with mctx := info.mctxAfter }, info.goalsAfter) for act in (tacticSeqCodeActionExt.getState snap.env).2 do try out := out ++ (← act params snap ctx i stk goals) catch _ => pure () | _ => unreachable! pure out
.lake/packages/batteries/Batteries/CodeAction/Misc.lean
module public meta import Lean.Elab.Tactic.Induction public meta import Batteries.Lean.Position public meta import Batteries.CodeAction.Attr public meta import Lean.Server.CodeActions.Provider public meta section /-! # Miscellaneous code actions This declares some basic tactic code actions, using the `@[tactic_code_action]` API. -/ namespace Batteries.CodeAction open Lean Meta Elab Server RequestM CodeAction /-- Return the syntax stack leading to `target` from `root`, if one exists. -/ def findStack? (root target : Syntax) : Option Syntax.Stack := do let range ← target.getRange? root.findStack? (·.getRange?.any (·.includes range)) (fun s => s.getKind == target.getKind && s.getRange? == range) /-- Constructs a hole with a kind matching the provided hole elaborator. -/ def holeKindToHoleString : (elaborator : Name) → (synthName : String) → String | ``Elab.Term.elabSyntheticHole, name => "?" ++ name | ``Elab.Term.elabSorry, _ => "sorry" | _, _ => "_" /-- Hole code action used to fill in a structure's field when specifying an instance. In the following: ```lean instance : Monad Id := _ ``` invoking the hole code action "Generate a (minimal) skeleton for the structure under construction." produces: ```lean instance : Monad Id where pure := _ bind := _ ``` and invoking "Generate a (maximal) skeleton for the structure under construction." produces: ```lean instance : Monad Id where map := _ mapConst := _ pure := _ seq := _ seqLeft := _ seqRight := _ bind := _ ``` -/ @[hole_code_action] partial def instanceStub : HoleCodeAction := fun _ snap ctx info => do let some ty := info.expectedType? | return #[] let .const name _ := (← info.runMetaM ctx (whnf ty)).getAppFn | return #[] unless isStructure snap.env name do return #[] let doc ← readDoc let fields := collectFields snap.env name #[] [] let only := !fields.any fun (_, auto) => auto let mkAutofix minimal := let eager := { title := s!"\ Generate a {if only then "" else if minimal then "(minimal) " else "(maximal) "}\ skeleton for the structure under construction." kind? := "quickfix" isPreferred? := minimal } let lazy? := some do let useWhere := do let _ :: (stx, _) :: _ ← findStack? snap.stx info.stx | none guard (stx.getKind == ``Parser.Command.declValSimple) stx[0].getPos? let holePos := useWhere.getD info.stx.getPos?.get! let (indent, isStart) := findIndentAndIsStart doc.meta.text.source holePos let indent := "\n".pushn ' ' indent let mut str := if useWhere.isSome then "where" else "{" let mut first := useWhere.isNone && isStart for (field, auto) in fields do if minimal && auto then continue if first then str := str ++ " " first := false else str := str ++ indent ++ " " let field := toString field str := str ++ s!"{field} := {holeKindToHoleString info.elaborator field}" if useWhere.isNone then if isStart then str := str ++ " }" else str := str ++ indent ++ "}" pure { eager with edit? := some <| .ofTextEdit doc.versionedIdentifier { range := doc.meta.text.utf8RangeToLspRange ⟨holePos, info.stx.getTailPos?.get!⟩ newText := str } } { eager, lazy? } pure <| if only then #[mkAutofix true] else #[mkAutofix true, mkAutofix false] where /-- Returns true if this field is an autoParam or optParam, or if it is given an optional value in a child struct. -/ isAutofillable (env : Environment) (fieldInfo : StructureFieldInfo) (stack : List Name) : Bool := fieldInfo.autoParam?.isSome || env.contains (mkDefaultFnOfProjFn fieldInfo.projFn) || stack.any fun struct => env.contains (mkDefaultFnOfProjFn (struct ++ fieldInfo.fieldName)) /-- Returns the fields of a structure, unfolding parent structures. -/ collectFields (env : Environment) (structName : Name) (fields : Array (Name × Bool)) (stack : List Name) : Array (Name × Bool) := (getStructureFields env structName).foldl (init := fields) fun fields field => if let some fieldInfo := getFieldInfo? env structName field then if let some substructName := fieldInfo.subobject? then collectFields env substructName fields (structName :: stack) else fields.push (field, isAutofillable env fieldInfo stack) else fields /-- Returns the explicit arguments given a type. -/ def getExplicitArgs : Expr → Array Name → Array Name | .forallE n _ body bi, args => getExplicitArgs body <| if bi.isExplicit then args.push n else args | _, args => args /-- Invoking hole code action "Generate a list of equations for a recursive definition" in the following: ```lean def foo : Expr → Unit := _ ``` produces: ```lean def foo : Expr → Unit := fun | .bvar deBruijnIndex => _ | .fvar fvarId => _ | .mvar mvarId => _ | .sort u => _ | .const declName us => _ | .app fn arg => _ | .lam binderName binderType body binderInfo => _ | .forallE binderName binderType body binderInfo => _ | .letE declName type value body nonDep => _ | .lit _ => _ | .mdata data expr => _ | .proj typeName idx struct => _ ``` -/ @[hole_code_action] def eqnStub : HoleCodeAction := fun _ snap ctx info => do let some ty := info.expectedType? | return #[] let .forallE _ dom .. ← info.runMetaM ctx (whnf ty) | return #[] let .const name _ := (← info.runMetaM ctx (whnf dom)).getAppFn | return #[] let some (.inductInfo val) := snap.env.find? name | return #[] let eager := { title := "Generate a list of equations for a recursive definition." kind? := "quickfix" } let doc ← readDoc pure #[{ eager lazy? := some do let holePos := info.stx.getPos?.get! let (indent, isStart) := findIndentAndIsStart doc.meta.text.source holePos let mut str := "fun" let indent := "\n".pushn ' ' (if isStart then indent else indent + 2) for ctor in val.ctors do let some (.ctorInfo ci) := snap.env.find? ctor | panic! "bad inductive" let ctor := toString (ctor.updatePrefix .anonymous) str := str ++ indent ++ s!"| .{ctor}" for arg in getExplicitArgs ci.type #[] do str := str ++ if arg.hasNum || arg.isInternal then " _" else s!" {arg}" str := str ++ s!" => {holeKindToHoleString info.elaborator ctor}" pure { eager with edit? := some <|.ofTextEdit doc.versionedIdentifier { range := doc.meta.text.utf8RangeToLspRange ⟨holePos, info.stx.getTailPos?.get!⟩ newText := str } } }] /-- Invoking hole code action "Start a tactic proof" will fill in a hole with `by done`. -/ @[hole_code_action] def startTacticStub : HoleCodeAction := fun _ _ _ info => do let holePos := info.stx.getPos?.get! let doc ← readDoc let indent := (findIndentAndIsStart doc.meta.text.source holePos).1 pure #[{ eager.title := "Start a tactic proof." eager.kind? := "quickfix" eager.edit? := some <|.ofTextEdit doc.versionedIdentifier { range := doc.meta.text.utf8RangeToLspRange ⟨holePos, info.stx.getTailPos?.get!⟩ newText := "by\n".pushn ' ' (indent + 2) ++ "done" } }] /-- The "Remove tactics after 'no goals'" code action deletes any tactics following a completed proof. ``` example : True := by trivial trivial -- <- remove this, proof is already done rfl ``` is transformed to ``` example : True := by trivial ``` -/ @[tactic_code_action*] def removeAfterDoneAction : TacticCodeAction := fun _ _ _ stk node => do let .node (.ofTacticInfo info) _ := node | return #[] unless info.goalsBefore.isEmpty do return #[] let _ :: (seq, i) :: _ := stk | return #[] let some stop := seq.getTailPos? | return #[] let some prev := (seq.setArgs seq.getArgs[:i]).getTailPos? | return #[] let doc ← readDoc let eager := { title := "Remove tactics after 'no goals'" kind? := "quickfix" isPreferred? := true edit? := some <|.ofTextEdit doc.versionedIdentifier { range := doc.meta.text.utf8RangeToLspRange ⟨prev, stop⟩ newText := "" } } pure #[{ eager }] /-- Similar to `getElimExprInfo`, but returns the names of binders instead of just the numbers; intended for code actions which need to name the binders. -/ def getElimExprNames (elimType : Expr) : MetaM (Array (Name × Array Name)) := do -- let inductVal ← getConstInfoInduct inductName -- let decl ← getConstInfo declName forallTelescopeReducing elimType fun xs type => do let motive := type.getAppFn let targets := type.getAppArgs let motiveType ← inferType motive let mut altsInfo := #[] for _h : i in [:xs.size] do let x := xs[i] if x != motive && !targets.contains x then let xDecl ← x.fvarId!.getDecl if xDecl.binderInfo.isExplicit then let args ← forallTelescopeReducing xDecl.type fun args _ => do let lctx ← getLCtx pure <| args.filterMap fun y => let yDecl := (lctx.find? y.fvarId!).get! if yDecl.binderInfo.isExplicit then some yDecl.userName else none altsInfo := altsInfo.push (xDecl.userName, args) pure altsInfo /-- Finds the `TermInfo` for an elaborated term `stx`. -/ def findTermInfo? (node : InfoTree) (stx : Term) : Option TermInfo := match node.findInfo? fun | .ofTermInfo i => i.stx.getKind == stx.raw.getKind && i.stx.getRange? == stx.raw.getRange? | _ => false with | some (.ofTermInfo info) => pure info | _ => none /-- Invoking tactic code action "Generate an explicit pattern match for 'induction'" in the following: ```lean example (x : Nat) : x = x := by induction x ``` produces: ```lean example (x : Nat) : x = x := by induction x with | zero => sorry | succ n ih => sorry ``` It also works for `cases`. -/ @[tactic_code_action Parser.Tactic.cases Parser.Tactic.induction] def casesExpand : TacticCodeAction := fun _ snap ctx _ node => do let .node (.ofTacticInfo info) _ := node | return #[] let (targets, induction, using_, alts) ← match info.stx with | `(tactic| cases $[$[$_ :]? $targets],* $[using $u]? $(alts)?) => pure (targets, false, u, alts) | `(tactic| induction $[$[$_ :]? $targets],* $[using $u]? $[generalizing $_*]? $(alts)?) => pure (targets, true, u, alts) | _ => return #[] let some discrInfos := targets.mapM (findTermInfo? node) | return #[] let some discr₀ := discrInfos[0]? | return #[] let mut some ctors ← discr₀.runMetaM ctx do let targets := discrInfos.map (·.expr) match using_ with | none => if tactic.customEliminators.get (← getOptions) then if let some elimName ← getCustomEliminator? targets induction then return some (← getElimExprNames (← getConstInfo elimName).type) matchConstInduct (← whnf (← inferType discr₀.expr)).getAppFn (fun _ => failure) fun val _ => do let elimName := if induction then mkRecName val.name else mkCasesOnName val.name return some (← getElimExprNames (← getConstInfo elimName).type) | some u => let some info := findTermInfo? node u | return none return some (← getElimExprNames (← inferType info.expr)) | return #[] let mut fallback := none if let some alts := alts then if let `(Parser.Tactic.inductionAlts| with $(_)? $alts*) := alts then for alt in alts do match alt with | `(Parser.Tactic.inductionAlt| | _ $_* => $fb) => fallback := fb.raw.getRange? | `(Parser.Tactic.inductionAlt| | $id:ident $_* => $_) => ctors := ctors.filter (fun x => x.1 != id.getId) | _ => pure () if ctors.isEmpty then return #[] let tacName := info.stx.getKind.updatePrefix .anonymous let eager := { title := s!"Generate an explicit pattern match for '{tacName}'." kind? := "quickfix" } let doc ← readDoc pure #[{ eager lazy? := some do let tacPos := info.stx.getPos?.get! let endPos := doc.meta.text.utf8PosToLspPos info.stx.getTailPos?.get! let indent := "\n".pushn ' ' (findIndentAndIsStart doc.meta.text.source tacPos).1 let (startPos, str') := if alts.isSome then let stx' := if fallback.isSome then info.stx.modifyArg (if induction then 4 else 3) (·.modifyArg 0 (·.modifyArg 2 (·.modifyArgs (·.filter fun s => !(s matches `(Parser.Tactic.inductionAlt| | _ $_* => $_)))))) else info.stx (doc.meta.text.utf8PosToLspPos stx'.getTailPos?.get!, "") else (endPos, " with") let fallback := if let some ⟨startPos, endPos⟩ := fallback then String.Pos.Raw.extract doc.meta.text.source startPos endPos else "sorry" let newText := Id.run do let mut str := str' for (name, args) in ctors do let mut ctor := toString name if let some _ := (Parser.getTokenTable snap.env).find? ctor then ctor := s!"{idBeginEscape}{ctor}{idEndEscape}" str := str ++ indent ++ s!"| {ctor}" -- replace n_ih with just ih if there is only one let args := if induction && args.foldl (fun c n => if n.eraseMacroScopes.getString!.endsWith "_ih" then c+1 else c) 0 == 1 then args.map (fun n => if !n.hasMacroScopes && n.getString!.endsWith "_ih" then `ih else n) else args for arg in args do str := str ++ if arg.hasNum || arg.isInternal then " _" else s!" {arg}" str := str ++ s!" => " ++ fallback str pure { eager with edit? := some <|.ofTextEdit doc.versionedIdentifier { range := ⟨startPos, endPos⟩ newText } } }] /-- The "Add subgoals" code action puts `· done` subgoals for any goals remaining at the end of a proof. ``` example : True ∧ True := by constructor -- <- here ``` is transformed to ``` example : True ∧ True := by constructor · done · done ``` -/ def addSubgoalsActionCore (params : Lsp.CodeActionParams) (i : Nat) (stk : Syntax.Stack) (goals : List MVarId) : RequestM (Array LazyCodeAction) := do -- If there are zero goals remaining, no need to do anything -- If there is one goal remaining, the user can just keep typing and subgoals are not helpful unless goals.length > 1 do return #[] let seq := stk.head!.1 let nargs := (seq.getNumArgs + 1) / 2 unless i == nargs do -- only trigger at the end of a block -- or if there is only a `done` or `sorry` terminator unless i + 1 == nargs && [ ``Parser.Tactic.done, ``Parser.Tactic.tacticSorry, ``Parser.Tactic.tacticAdmit ].contains seq[2*i].getKind do return #[] let some startPos := seq[0].getPos? true | return #[] let doc ← readDoc let eager := { title := "Add subgoals", kind? := "quickfix" } pure #[{ eager lazy? := some do let indent := "\n".pushn ' ' (doc.meta.text.toPosition startPos).column let mut (range, newText) := (default, "") if let some tac := seq.getArgs[2*i]? then let some range2 := tac.getRange? true | return eager range := range2 else let trimmed := seq.modifyArgs (·[:2*i]) let some tail := trimmed.getTailPos? true | return eager (range, newText) := (⟨tail, tail⟩, indent) let cursor := doc.meta.text.lspPosToUtf8Pos params.range.end if range.stop ≤ cursor && cursor.1 ≤ range.stop.1 + trimmed.getTrailingSize then range := { range with stop := cursor } newText := newText ++ "· done" for _ in goals.tail! do newText := newText ++ indent ++ "· done" pure { eager with edit? := some <|.ofTextEdit doc.versionedIdentifier { range := doc.meta.text.utf8RangeToLspRange range newText } } }] @[inherit_doc addSubgoalsActionCore, tactic_code_action] def addSubgoalsSeqAction : TacticSeqCodeAction := fun params _ _ => addSubgoalsActionCore params -- This makes sure that the addSubgoals action also triggers -- when the cursor is on the final `done` of a tactic block @[inherit_doc addSubgoalsActionCore, tactic_code_action Parser.Tactic.done Parser.Tactic.tacticSorry Parser.Tactic.tacticAdmit] def addSubgoalsAction : TacticCodeAction := fun params _ _ stk node => do let (_ :: (seq, i) :: stk@(_ :: t :: _), .node (.ofTacticInfo info) _) := (stk, node) | return #[] unless t.1.getKind == ``Parser.Tactic.tacticSeq do return #[] addSubgoalsActionCore params (i/2) ((seq, 0) :: stk) info.goalsBefore