Warning: this is an htmlized version!
The original is here, and
the conversion rules are here.
######
#
# E-scripts on the Lean theorem prover / proof assistant.
#
# Note 1: use the eev command (defined in eev.el) and the
# ee alias (in my .zshrc) to execute parts of this file.
# Executing this file as a whole makes no sense.
# An introduction to eev can be found here:
#
#   (find-eev-quick-intro)
#   http://angg.twu.net/eev-intros/find-eev-quick-intro.html
#
# Note 2: be VERY careful and make sure you understand what
# you're doing.
#
# Note 3: If you use a shell other than zsh things like |&
# and the for loops may not work.
#
# Note 4: I always run as root.
#
# Note 5: some parts are too old and don't work anymore. Some
# never worked.
#
# Note 6: the definitions for the find-xxxfile commands are on my
# .emacs.
#
# Note 7: if you see a strange command check my .zshrc -- it may
# be defined there as a function or an alias.
#
# Note 8: the sections without dates are always older than the
# sections with dates.
#
# This file is at <http://angg.twu.net/e/lean.e>
#           or at <http://angg.twu.net/e/lean.e.html>.
#        See also <http://angg.twu.net/emacs.html>,
#                 <http://angg.twu.net/.emacs[.html]>,
#                 <http://angg.twu.net/.zshrc[.html]>,
#                 <http://angg.twu.net/escripts.html>,
#             and <http://angg.twu.net/>.
#
#######



# «.lean4-mode-melpa»		(to "lean4-mode-melpa")
# «.lean4-mode-vc»		(to "lean4-mode-vc")
# «.feb2024»			(to "feb2024")
# «.zulip»			(to "zulip")
# «.elan»			(to "elan")
# «.install-2024»		(to "install-2024")
# «.lean4»			(to "lean4")
# «.lean4-git»			(to "lean4-git")
#   «.ee-rstdoc-:lean4»		(to "ee-rstdoc-:lean4")
#   «.:lean4»			(to ":lean4")
# «.lake»			(to "lake")
# «.lake-new-lake-build»	(to "lake-new-lake-build")
# «.lake-env»			(to "lake-env")
# «.lake-CLI»			(to "lake-CLI")
# «.lake-new-greeting»		(to "lake-new-greeting")
# «.lake-current-directory»	(to "lake-current-directory")
# «.cache-mathlib»		(to "cache-mathlib")
# «.lean4-mode»			(to "lean4-mode")
# «.lean-mode»			(to "lean-mode")
# «.lsp-server-exited-restart»	(to "lsp-server-exited-restart")
# «.lsp-yasnippet»		(to "lsp-yasnippet")
# «.mode-line»			(to "mode-line")
# «.topos»			(to "topos")
# «.diagram-chasing»		(to "diagram-chasing")
# «.prelude»			(to "prelude")
# «.rec_on»			(to "rec_on")
# «.alectryon»			(to "alectryon")
# «.nng4»			(to "nng4")
# «.lean4game»			(to "lean4game")
# «.natural-number-game»	(to "natural-number-game")
# «.real-number-game»		(to "real-number-game")
# «.set-theory-game»		(to "set-theory-game")
# «.mathsinlean»		(to "mathsinlean")
# «.:leanmaths»			(to ":leanmaths")
# «.mathsinlean-build»		(to "mathsinlean-build")
# «.mathsinlean-source»		(to "mathsinlean-source")
# «.mathzoo»			(to "mathzoo")
# «.mathlib»			(to "mathlib")
# «.mathlib4»			(to "mathlib4")
# «.mathlib4-greeting»		(to "mathlib4-greeting")
# «.mathlib-calculus»		(to "mathlib-calculus")
# «.tactics-list»		(to "tactics-list")
# «.tactics-in-ND»		(to "tactics-in-ND")
# «.vernacular»			(to "vernacular")
# «.fplean4»			(to "fplean4")
#
# «.3-essential»		(to "3-essential")
# «.3-essential-way-1»		(to "3-essential-way-1")
# «.3-essential-way-2»		(to "3-essential-way-2")
# «.3-essential-way-3»		(to "3-essential-way-3")
# «.abbrev»			(to "abbrev")
# «.addDecl»			(to "addDecl")
# «.anonymous»			(to "anonymous")
# «.antiquotation»		(to "antiquotation")
# «.Array»			(to "Array")
# «.assign»			(to "assign")
# «.attributes»			(to "attributes")
# «.axiom»			(to "axiom")
# «.batteries»			(to "batteries")
# «.builtin_initialize»		(to "builtin_initialize")
# «.check»			(to "check")
# «.check-polymorphic»		(to "check-polymorphic")
# «.class»			(to "class")
# «.class-extends»		(to "class-extends")
# «.command»			(to "command")
# «.constant»			(to "constant")
# «.backtick»			(to "backtick")
#   «.double-backtick»		(to "double-backtick")
# «.backtick-syntaxcat»		(to "backtick-syntaxcat")
# «.Bind»			(to "Bind")
# «.binop»			(to "binop")
# «.calc»			(to "calc")
# «.def»			(to "def")
# «.check»			(to "check")
# «.checksyntax»		(to "checksyntax")
# «.checksyntax-test»		(to "checksyntax-test")
# «.coercion»			(to "coercion")
# «.CommandElabM»		(to "CommandElabM")
# «.company»			(to "company")
# «.CoreM»			(to "CoreM")
# «.dbg_trace»			(to "dbg_trace")
# «.declare_syntax_cat»		(to "declare_syntax_cat")
# «.denoteArith»		(to "denoteArith")
# «.deriving»			(to "deriving")
# «.discard»			(to "discard")
# «.doc-comments»		(to "doc-comments")
# «.do-iteration»		(to "do-iteration")
# «.do-notation»		(to "do-notation")
# «.dotdot»			(to "dotdot")
# «.eglot»			(to "eglot")
# «.elab»			(to "elab")
# «.elabIMP»			(to "elabIMP")
# «.elab_rules»			(to "elab_rules")
# «.elab-term»			(to "elab-term")
# «.elab-type»			(to "elab-type")
# «.eldoc»			(to "eldoc")
# «.Environment»		(to "Environment")
# «.exceptions»			(to "exceptions")
# «.explicit-arguments»		(to "explicit-arguments")
#   «.implicit-arguments»	(to "implicit-arguments")
# «.exploring-data»		(to "exploring-data")
# «.exploring-data-2»		(to "exploring-data-2")
# «.export»			(to "export")
# «.Expr»			(to "Expr")
# «.extends»			(to "extends")
# «.extern»			(to "extern")
# «.extractFrom»		(to "extractFrom")
# «.eval»			(to "eval")
# «.example»			(to "example")
# «.feline»			(to "feline")
# «.FFI»			(to "FFI")
# «.FilePath»			(to "FilePath")
# «.FirstTokens»		(to "FirstTokens")
# «.fun»			(to "fun")
# «.Functor»			(to "Functor")
# «.getCurrNamespace»		(to "getCurrNamespace")
# «.guard_msgs»			(to "guard_msgs")
# «.guillemets»			(to "guillemets")
# «.HashMap»			(to "HashMap")
# «.have»			(to "have")
# «.heterogeneous»		(to "heterogeneous")
# «.Id.run»			(to "Id.run")
# «.if-let»			(to "if-let")
# «.import»			(to "import")
# «.import-problem»		(to "import-problem")
# «.indentation»		(to "indentation")
# «.inductive»			(to "inductive")
# «.inductive-Arith»		(to "inductive-Arith")
# «.inductive-Expr»		(to "inductive-Expr")
# «.inductive-List»		(to "inductive-List")
# «.inductive-N»		(to "inductive-N")
# «.inductive-Nat»		(to "inductive-Nat")
#   «.inductive-myNat»		(to "inductive-myNat")
# «.inductive-Option»		(to "inductive-Option")
# «.inductive-Syntax»		(to "inductive-Syntax")
# «.inferInstance»		(to "inferInstance")
# «.inferType»			(to "inferType")
# «.infix»			(to "infix")
# «.infixl»			(to "infixl")
# «.infixr»			(to "infixr")
# «.info-scp-mainModule»	(to "info-scp-mainModule")
# «.Inhabited»			(to "Inhabited")
# «.initialize»			(to "initialize")
# «.instance»			(to "instance")
# «.instance-implicits»		(to "instance-implicits")
# «.instance-Monad-List»	(to "instance-Monad-List")
# «.interpolatedStr»		(to "interpolatedStr")
# «.IO»				(to "IO")
# «.IO.print»			(to "IO.print")
# «.IO.println»			(to "IO.println")
# «.IO.Process.output»		(to "IO.Process.output")
# «.Lake.Load»			(to "Lake.Load")
# «.latin-cross»		(to "latin-cross")
# «.LawfulFunctor»		(to "LawfulFunctor")
# «.leading-dot-notation»	(to "leading-dot-notation")
# «.leading_parser»		(to "leading_parser")
# «.Lean.Parser.Category»	(to "Lean.Parser.Category")
# «.lean-type-theory»		(to "lean-type-theory")
# «.let»			(to "let")
# «.let_fun»			(to "let_fun")
# «.let-mut»			(to "let-mut")
# «.letterlike»			(to "letterlike")
# «.Linter»			(to "Linter")
# «.List»			(to "List")
# «.logInfo»			(to "logInfo")
# «.macro»			(to "macro")
# «.map»			(to "map")
# «.mapAddOneNil»		(to "mapAddOneNil")
# «.match»			(to "match")
# «.match-bar»			(to "match-bar")
# «.mdbook»			(to "mdbook")
# «.mdgen»			(to "mdgen")
# «.meta-if»			(to "meta-if")
# «.minted»			(to "minted")
# «.mkSyntaxQuotation»		(to "mkSyntaxQuotation")
# «.Monad»			(to "Monad")
# «.Monad-map»			(to "Monad-map")
# «.Monad-S»			(to "Monad-S")
# «.modules»			(to "modules")
# «.mutual»			(to "mutual")
# «.mySpecialCheck»		(to "mySpecialCheck")
# «.Name»			(to "Name")
# «.namespace»			(to "namespace")
#   «.section»			(to "section")
#   «.open»			(to "open")
# «.notation»			(to "notation")
# «.opaque»			(to "opaque")
# «.open»			(to "open")
# «.Options»			(to "Options")
# «.orelse»			(to "orelse")
# «.outParam»			(to "outParam")
# «.p123456»			(to "p123456")
# «.Partax»			(to "Partax")
# «.Partax-match_stx2»		(to "Partax-match_stx2")
# «.parse_term»			(to "parse_term")
# «.partial»			(to "partial")
# «.partial-mutual»		(to "partial-mutual")
# «.polymorphism»		(to "polymorphism")
# «.posOrNegThree»		(to "posOrNegThree")
# «.postulate»			(to "postulate")
# «.pp.notation»		(to "pp.notation")
# «.pp.universes»		(to "pp.universes")
# «.pratt-parser»		(to "pratt-parser")
# «.precedence»			(to "precedence")
# «.print»			(to "print")
# «.print-inductive»		(to "print-inductive")
# «.Prod»			(to "Prod")
# «.project»			(to "project")
# «.Pure»			(to "Pure")
# «.Range»			(to "Range")
# «.ReaderT»			(to "ReaderT")
# «.reduce»			(to "reduce")
# «.repl»			(to "repl")
# «.Repr»			(to "Repr")
# «.repr-type»			(to "repr-type")
# «.runActions»			(to "runActions")
# «.runCmd»			(to "runCmd")
# «.run_cmd»			(to "run_cmd")
# «.runParserCategory»		(to "runParserCategory")
# «.runTermElabM»		(to "runTermElabM")
# «.rw»				(to "rw")
# «.saveState»			(to "saveState")
# «.scoped-syntax»		(to "scoped-syntax")
# «.semi-output»		(to "semi-output")
# «.server»			(to "server")
# «.show»			(to "show")
# «.show-from-do»		(to "show-from-do")
# «.sleep1»			(to "sleep1")
# «.specialize»			(to "specialize")
# «.State»			(to "State")
# «.Std.Format»			(to "Std.Format")
# «.string-interpolation»	(to "string-interpolation")
# «.structure»			(to "structure")
# «.structures»			(to "structures")
# «.structure-like»		(to "structure-like")
# «.stx»			(to "stx")
# «.syntax-command»		(to "syntax-command")
# «.syntax-parser»		(to "syntax-parser")
# «.syntax-name»		(to "syntax-name")
# «.synth»			(to "synth")
# «.tactic_expand1»		(to "tactic_expand1")
# «.tagged-subgoals»		(to "tagged-subgoals")
# «.telescopes»			(to "telescopes")
# «.termination»		(to "termination")
# «.termParser»			(to "termParser")
# «.theorem»			(to "theorem")
# «.toolchains»			(to "toolchains")
# «.ToString»			(to "ToString")
# «.tpil-p38»			(to "tpil-p38")
# «.trace.Elab.command»		(to "trace.Elab.command")
# «.trace.Elab.info»		(to "trace.Elab.info")
# «.try-catch»			(to "try-catch")
# «.TSyntax»			(to "TSyntax")
# «.typeclass-seach»		(to "typeclass-seach")
# «.typeof»			(to "typeof")
# «.underscore»			(to "underscore")
# «.variable»			(to "variable")
# «.where»			(to "where")
# «.whnf»			(to "whnf")
#
# «.delaborator-diagram»	(to "delaborator-diagram")
# «.reference-manual»		(to "reference-manual")
#   «.:leanref»			(to ":leanref")
# «.metaprogramming»		(to "metaprogramming")
#   «.:leanmeta»		(to ":leanmeta")
# «.metaprogramming-book.yml»	(to "metaprogramming-book.yml")
# «.metaprogramming-toolchain»	(to "metaprogramming-toolchain")
# «.TermElabM»			(to "TermElabM")
# «.tpil»			(to "tpil")
# «.useandabuseoip»		(to "useandabuseoip")
# «.ullrichmp»			(to "ullrichmp")
# «.mechanics-of-proof»		(to "mechanics-of-proof")
# «.:mechprf»			(to ":mechprf")
# «.Colorized»			(to "Colorized")
# «.leandojo»			(to "leandojo")
# «.do-unchained»		(to "do-unchained")




https://leanprover.github.io/
https://leanprover.github.io/tutorial/
https://leanprover.github.io/download/debian78.html

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# Dependencies
sudo apt-get install libstdc++-4.8-dev libgmp-dev libmpfr-dev liblua5.2-dev ninja-build
sudo dpkg -i /tmp/lean*.deb

# (find-status   "lean")
# (find-vldifile "lean.list")
# (find-udfile   "lean/")

# (find-sitelispfile "lean/")
# (find-sitelispfile "lean/lean-mode.el")
# (find-sitelispfile "lean/lean-mode.el" ";; Automatically use lean-mode for")
# (find-sitelispfile "lean/load-lean.el")

# (find-fline "/usr/lib/lean/")
# (find-fline "/usr/lib/lean/hott/")
# (find-fline "/usr/lib/lean/hott/book.md")
# (find-fline "/usr/lib/lean/library/")
# (find-fline "/usr/lib/lean/library/logic/logic.md")


https://leanprover.github.io/documentation/
http://leanprover.github.io/presentations/20150123_lean-mode/lean-mode.pdf
https://leanprover.github.io/tutorial/tutorial.pdf
https://leanprover.github.io/tutorial/quickref.pdf
https://github.com/leanprover/lean
https://github.com/leanprover/lean/blob/master/doc/lean/tutorial.org
https://github.com/leanprover/lean/blob/master/src/emacs/README.md


https://jiggerwit.wordpress.com/2018/09/18/a-review-of-the-lean-theorem-prover/ ***

https://xenaproject.wordpress.com/2020/02/09/lean-is-better-for-proper-maths-than-all-the-other-theorem-provers/
https://xenaproject.wordpress.com/2020/02/09/where-is-the-fashionable-mathematics/
https://xenaproject.wordpress.com/2020/04/30/the-invisible-map/
https://xenaproject.wordpress.com/2020/06/27/teaching-dependent-type-theory-to-4-year-olds-via-mathematics/amp/

https://xenaproject.wordpress.com/2021/01/21/formalising-mathematics-an-introduction/ pictures as eefective guides ***
https://xenaproject.wordpress.com/2021/04/18/induction-on-equality/




#####
#
# lean4-mode-melpa
# 2024mar10
#
#####

# «lean4-mode-melpa»  (to ".lean4-mode-melpa")
# (find-epackage-links 'lean4-mode "lean4mode" t)
# (find-epackages      'lean4-mode)
# (find-epackage       'lean4-mode)

# (package-refresh-contents)
# (package-install 'lean4-mode)
# (find-epackage   'lean4-mode)
# (package-delete (ee-package-desc 'lean4-mode))

# (code-c-d "lean4mode" "~/.emacs.d/elpa/lean4-mode/")
# (find-lean4modefile "")



#####
#
# lean4-mode-vc
# 2024mar10
#
#####

# «lean4-mode-vc»  (to ".lean4-mode-vc")
# (find-epackage-links 'lean4-mode "lean4mode" t)
# (find-epackage       'lean4-mode)
# (package-vc-install "https://github.com/leanprover-community/lean4-mode")
# (code-c-d "lean4mode" "~/.emacs.d/elpa/lean4-mode/")
# (find-lean4modefile "")
# (find-lean4modefile "README.md" "Trying It Out")
# https://github.com/leanprover-community/lean4-mode?tab=readme-ov-file#trying-it-out
# (find-ekeymapdescr lean4-mode-map "C-c C-k" "quail-show-key")

 C-c C-k      show the keystroke needed to input the symbol under the cursor
 C-c C-d      recompile & reload imports (`lean4-refresh-file-dependencies`)
 C-c C-x      execute Lean in stand-alone mode (`lean4-std-exe`)
 C-c C-p C-l  builds package with lake (`lean4-lake-build`)
 C-c C-i      toggle info view showing goals and errors at point (`lean4-toggle-info-buffer`)
 C-c ! n      flycheck: go to next error
 C-c ! p      flycheck: go to previous error

  →×αβ∧∨↔¬





#####
#
# feb2024
# 2024feb22
#
#####

# «feb2024»  (to ".feb2024")
# (find-es "emacs" "flycheck")
# (find-angg "LEAN/a.lean")

# (find-fline "~/.emacs.d/elpa/lean4-mode/")
# (find-fline "~/.emacs.d/elpa/lean4-mode/lean4-fringe.el" "(require 'lsp-mode)")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd ~/.emacs.d/elpa/lean4-mode/
git pull

* (byte-recompile-directory "~/.emacs.d/elpa/lean4-mode/")


# Source file ‘/home/edrx/.emacs.d/elpa/lean4-mode/lean4-mode.el’ newer than byte-compiled file; using older file
# File mode specification error: (file-missing Cannot open load file No such file or directory ht)
# (find-efunctiondescr   'byte-compile-file)
# (find-efunction        'byte-compile-file)
# (find-elnode "Index" "* byte-compile-file:")
# (find-efunction-links 'byte-recompile-directory)


# (find-epackage-links 'spinner)
# (find-epackage-links 'ht)
# (find-epackage       'ht)
# (code-c-d "ht" "{d}")

https://github.com/Wilfred/ht.el




#####
#
# zulip
# 2023jun24
#
#####

# «zulip»  (to ".zulip")
# https://leanprover.zulipchat.com/




#####
#
# elan
# 2023jun22
#
#####

# «elan»  (to ".elan")
# «install-2024»  (to ".install-2024")
# (find-angg ".emacs" "lean4")
# https://leanprover-community.github.io/install/debian.html
# https://leanprover-community.github.io/install/debian_details.html
# https://github.com/leanprover/elan
# https://proofassistants.stackexchange.com/questions/2/how-do-i-install-lean-4
# (find-git-links "https://github.com/leanprover/elan" "elan")
# (code-c-d "elan" "~/usrc/elan/")
# (find-elanfile "")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "/tmp/elan-install/")
rm -Rv /tmp/elan-install/
mkdir  /tmp/elan-install/
cd     /tmp/elan-install/
curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf \
  | sh -s -- --default-toolchain leanprover/lean4:stable

# (find-fline "~/.profile")
# (find-fline "~/.zprofile")

Elan is installed now. Great!

To get started you need Elan's bin directory ($HOME/.elan/bin) in your PATH 
environment variable. Next time you log in this will be done automatically.

To configure your current shell run source $HOME/.elan/env


# (code-c-d "elan4lean" "~/.elan/toolchains/leanprover--lean4---stable/src/lean/")
# (find-elan4leanfile "")
# (find-sh "find ~/.elan/ | sort")
rm -Rfv ~/.elan/

elan
elan show
# elan default leanprover/lean4:stable
w lake
lake

# (find-fline "/home/edrx/.elan/bin/")

# Welcome to Lean!
# 
# This will download and install Elan, a tool for managing different Lean 
# versions used in packages you create or download. It will also install a 
# default version of Lean and its package manager, leanpkg, for editing files not
# belonging to any package.
# 
# It will add the leanpkg, lean, and elan commands to Elan's bin directory, 
# located at:
# 
#   /home/edrx/.elan/bin
# 
# This path will then be added to your PATH environment variable by modifying the
# profile files located at:
# 
#   /home/edrx/.profile
#   /home/edrx/.zprofile
# 
# You can uninstall at any time with elan self uninstall and these changes will 
# be reverted.
# 
# Current installation options:
# 
#      default toolchain: leanprover/lean4:nightly
#   modify PATH variable: yes
# 
# 1) Proceed with installation (default)
# 2) Customize installation
# 3) Cancel installation



* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# rm -Rfv ~/usrc/elan/
cd      ~/usrc/
git clone https://github.com/leanprover/elan
cd      ~/usrc/elan/

# (code-c-d "elan" "~/usrc/elan/")
# (find-elanfile "")
# (find-elanfile "elan-init.sh")

# (find-fline "~/.elan/")
# (find-fline "~/.profile")
# (find-fline "~/.zprofile")



#####
#
# reinstall-2024
# 2024may16
#
#####

# «.reinstall-2024»	(to "reinstall-2024")
# «reinstall-2024»  (to ".reinstall-2024")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
du -ch ~/.elan/
rm -Rv ~/.elan/




#####
#
# lean4
# 2023jun22
#
#####

# «lean4»      (to ".lean4")
# «lean4-git»  (to ".lean4-git")
# https://github.com/leanprover/lean4
# https://www.reddit.com/r/haskell/comments/z55hha/review_of_lean_4/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# rm -Rfv ~/bigsrc/lean4/
cd      ~/bigsrc/
git clone https://github.com/leanprover/lean4
cd      ~/bigsrc/lean4/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd      ~/bigsrc/lean4/
git pull
git clean -dfx
git reset --hard
find * | sort > .files
wc              .files

export PAGER=cat
git branch --list -a
git for-each-ref
git log --oneline --graph --all -20

# (find-fline "~/bigsrc/")
# (find-fline "~/bigsrc/lean4/")
# (find-gitk  "~/bigsrc/lean4/")

# (code-c-d "lean4" "~/bigsrc/lean4/")
# (find-lean4sh "find * -type d | sort")
# (find-lean4sh "find * | sort | grep -i check")
# (find-lean4sh "find * | sort | grep -i notation")
# (find-lean4sh "find * | sort | grep -i synthesize")
# (find-lean4file "")
# (find-lean4file ".files")
# (find-lean4file "doc/")
# (find-lean4file "doc/setup.md")
# (find-lean4file "doc/quickstart.md")
# (find-lean4file "doc/quickstart.md" "lake init foo")
# (find-lean4file "doc/sections.md")
# (find-lean4file "doc/dev/mdbook.md")
# https://lean-lang.org/lean4/doc/dev/mdbook.html

Quickstart:        https://github.com/leanprover/lean4/blob/master/doc/quickstart.md
Walkthrough installation video:  https://www.youtube.com/watch?v=yZo6k48L0VY
Quick tour video:  https://youtu.be/zyXtbb_eYbY
Homepage:          https://leanprover.github.io
Theorem Proving Tutorial:        https://leanprover.github.io/theorem_proving_in_lean4/
Functional Programming in Lean:  https://leanprover.github.io/functional_programming_in_lean/
Manual:            https://leanprover.github.io/lean4/doc/
Release notes:     RELEASES.md
Examples:          https://leanprover.github.io/lean4/doc/examples.html
FAQ:               https://leanprover.github.io/lean4/doc/faq.html
Setting Up Lean:   https://leanprover.github.io/lean4/doc/setup.html

https://github.com/leanprover/lean4/blob/master/doc/setup.md#basic-setup

$ elan self update  # in case you haven't updated elan in a while
# download & activate latest Lean 4 stable release (https://github.com/leanprover/lean4/releases)
$ elan default leanprover/lean4:stable

elan self update
elan default leanprover/lean4:stable

# download & activate latest Lean 4 stable release (https://github.com/leanprover/lean4/releases)



#####
#
# ee-rstdoc-:lean4
# 2024may23
#
#####

# «ee-rstdoc-:lean4»  (to ".ee-rstdoc-:lean4")
# «:lean4»  (to ".:lean4")
# (find-angg ".emacs"         "ee-rstdoc-:lean4")
# (find-angg ".emacs.lean.el" "ee-rstdoc-:lean4")
# (find-wgetrecursive-links "https://lean-lang.org/lean4/doc/")
# (to "lean4-git")
# (find-code-rstdoc :lean4)
# (find-lean4doc  "whatIsLean")
# (find-lean4docw "whatIsLean")
# (find-lean4docr "whatIsLean.md")




#####
#
# lake
# 2024mar10
#
#####

# «lake»  (to ".lake")
# (find-angg ".emacs.papers" "fplean4")
# (find-angg ".emacs.papers" "fplean4" "75" "Starting a Project")
# (find-lean4doc  "setup#lake")
# (find-lean4docr "setup.md#lake")
# (find-fplean4doc  "hello-world/starting-a-project#first-steps")
# (find-fplean4docr "hello-world/starting-a-project" "## First steps")
# (find-fplean4docr "hello-world/starting-a-project" "`lake init` instead of `lake new`")

# Deprecated, merged into Lean4:
#   https://github.com/leanprover/lake
#   (find-git-links "https://github.com/leanprover/lake" "lake")
#   (code-c-d "lake" "~/usrc/lake/")
# See: (to "IO.Process.output")

# (find-lean4file "")
# (find-lean4sh "find * | sort")
# (find-lean4sh "find * | sort | grep -i lake")
# (find-lean4file "src/Lean/Util/LakePath.lean")
# (find-lean4file "src/lake/")
# (find-lean4file "src/lake/Lake.lean")
# (find-lean4file "src/lake/Lake/")
# (find-lean4file "src/lake/README.md")

# (find-lakefile "")
# (find-lakefile "README.md")
# (find-lakesh "find * | sort")




#####
#
# Testing lake with "lake new greeting"
# 2023jun25
#
#####

# «lake-new-greeting»  (to ".lake-new-greeting")
# (to "project")
# (to "modules")
# (to "mathlib4-greeting")
# (find-angg ".emacs.papers" "fplean4")
# (find-fplean4doc  "hello-world/starting-a-project")
# (find-fplean4docr "hello-world/starting-a-project")
# (find-fplean4docr "hello-world/starting-a-project" "lake new greeting")
# (find-fplean4page 75 "Starting a Project")
# (find-fplean4text 75 "Starting a Project")
# (find-fplean4page 76  "import «Greeting»")
# (find-fplean4text 76  "import «Greeting»")

# (code-c-d "grg" "/tmp/gr/greeting/")
# (find-grgfile "")
# (find-grgfile "lakefile.lean" "@[default_target]")
# (find-lean4prefile "lake/Lake/DSL/Attributes.lean" "initialize defaultTargetAttr")
# (to "initialize")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "/tmp/gr/")
rm -Rfv /tmp/greeting/
rm -Rfv /tmp/gr/
mkdir   /tmp/gr/
cd      /tmp/gr/
lake new greeting
cd      /tmp/gr/greeting/

# lean --run Main.lean
# lean --run Greeting.lean

find * | sort |  tee of0
lake build    |& tee olb
find * | sort |  tee of1
comm of0 of1

laf
find  build | sort
      build/bin/greeting
cp -v build/bin/greeting /tmp/greeting
cd /tmp/
./greeting

# (find-fline "/tmp/gr/greeting/")
# (find-fline "/tmp/gr/greeting/Main.lean")
# (find-fline "/tmp/gr/greeting/build/bin/")

w lake




#####
#
# Testing lake by running "lake new foo", "cd foo", and "lake build"
# 2024jun09
#
#####

# «lake-new-lake-build»  (to ".lake-new-lake-build")
lake-build lake build

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# (find-fline "/tmp/testlake/")
rm -Rfv /tmp/testlake/
mkdir   /tmp/testlake/
cd      /tmp/testlake/
lake new foo
find    /tmp/testlake/ | sort

cd      /tmp/testlake/foo/
lake build   |& tee olb

** (find-sh "find /tmp/testlake/           | sort")
** (find-sh "find /tmp/testlake/foo/.lake/ | sort")
*  (code-c-d "foo"      "/tmp/testlake/foo/")
*  (code-c-d "foobuild" "/tmp/testlake/foo/.lake/build/")
** (find-foofile "")
** (find-foobuildfile "")
** (find-foosh      "find * .lake/ | sort")
** (find-foosh      "find *        | sort")
** (find-foobuildsh "find *        | sort")

      /tmp/testlake/foo/.lake/build/bin/foo
cp -v /tmp/testlake/foo/.lake/build/bin/foo /tmp/testlake/foo.bin
      /tmp/testlake/foo.bin

# (find-foofile "")
# (find-foofile "Main.lean")
# (find-foofile "Foo.lean")
# (find-foofile "Foo/")
# (find-foofile "Foo/Basic.lean")




#####
#
# lake-env
# 2024jun10
#
#####

# «lake-env»  (to ".lake-env")
# (to "import-problem")
# (find-sh "lake --help" "env <cmd> <args>")
# (find-sh "lake --help env")
# (find-lean4prefile "lake/Lake/CLI/Help.lean" "env <cmd> <args>")
# (find-lean4prefile "lake/Lake/CLI/Help.lean" "def helpEnv :=")




#####
#
# lake-CLI
# 2024jun09
#
#####

# «lake-CLI»  (to ".lake-CLI")
# (find-fplean4page 76 "@[default_target]")
# (find-fplean4text 76 "@[default_target]")
# (find-fplean4doc  "hello-world/starting-a-project")
# (find-fplean4docr "hello-world/starting-a-project" "@[default_target]")
# (find-fplean4docr "hello-world/starting-a-project" "@[default_target]" "To build a target that is not annotated with `@[default_target]`")

# (find-lean4prefile "lake/Lake/CLI/Main.lean" "def lakeLongOption :")
# (find-lean4prefile "lake/Lake/CLI/Main.lean" "def lakeCli :")







#####
#
# Making lake import files in the current directory
# 2024jun07
#
#####

# «lake-current-directory»  (to ".lake-current-directory")
# (to "import")
# (to "Colorized")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Minimal.20setup.20for.20importing.20.2Elean.20files.20in.20the.20same.20director

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv /tmp/test/
mkdir   /tmp/test/
cd      /tmp/test/

cat > A.lean <<'%%%'
def a := 42
#eval a
%%%

cat > B.lean <<'%%%'
import A
#eval a
%%%

cat > lakefile.lean <<'%%%'
import Lake
open   Lake DSL
package  A
lean_lib A
%%%

lean A.lean     ;# 42
lean B.lean     ;# error
lake build
find * .lake/ | sort
lean B.lean     ;# error

# (find-fline "/tmp/test/")
# (find-fline "/tmp/test/A.lean")
# (find-fline "/tmp/test/B.lean")
# (find-fline "/tmp/test/lakefile.lean")
# (find-fline "~/LuaTreeLean/")
# (find-fline "~/LuaTreeLean/lakefile.lean")

cd ~/LuaTreeLean/
lean Test1.lean





#####
#
# cache-mathlib
# 2023jun26
#
#####

# «cache-mathlib»  (to ".cache-mathlib")
# (find-fline "~/.cache/mathlib/")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
du -c ~/.cache/mathlib/
find  ~/.cache/mathlib/
laf   ~/.cache/mathlib/




#####
#
# lean4-mode
# 2023jun22
#
#####

# «lean4-mode»  (to ".lean4-mode")
# https://github.com/leanprover/lean4-mode
# (find-es "emacs" "package-vc-install")
# (find-es "emacs" "lsp-mode")
# (package-vc-install "https://github.com/leanprover/lean4-mode")

# (find-epackage-links 'lean4-mode "lean4mode" t)
# (find-epackages      'lean4-mode)
# (find-epackage       'lean4-mode)
# (code-c-d "lean4mode" "~/.emacs.d/elpa/lean4-mode/")
# (find-lean4modefile "")
# (find-lean4modefile "README.md" "hovering")
# (find-lean4modefile "README.md" "C-c C-i" "toggle info view")
# (find-lean4modefile "lean4-input.el" "(defcustom lean4-input-inherit")






#####
#
# lean-mode
# 2021jul05
#
#####

# «lean-mode»  (to ".lean-mode")
# (find-epackages 'lean-mode)
# (find-epackage-links 'lean-mode)
# (find-epackage       'lean-mode)
# (code-c-d "leanmode" "~/.emacs.d/elpa/lean-mode-20210502.2049/")
# (find-leanmodefile "")
# (find-leanmodegrep "grep --color=auto -nH --null -e rootdir *.el")
# (find-efunction 'lean-get-rootdir)

https://leanprover.github.io/documentation/
https://leanprover.github.io/presentations/20150123_lean-mode/lean-mode.pdf
https://leanprover.github.io/tutorial/tutorial.pdf
https://leanprover.github.io/tutorial/quickref.pdf



#####
#
# mode-line
# 2024mar10
#
#####

# «mode-line»  (to ".mode-line")
# find-emodeline-links

("%e"
 mode-line-front-space

 (:propertize
  (""
   mode-line-mule-info
   mode-line-client
   mode-line-modified
   mode-line-remote
   mode-line-window-dedicated)
  display (min-width (6.0)))

 mode-line-frame-identification
 mode-line-buffer-identification
 "   "
 mode-line-position
 (project-mode-line project-mode-line-format)
 (vc-mode vc-mode)
 "  "
 mode-line-modes
 mode-line-misc-info
 mode-line-end-spaces)

# (find-evardescr 'mode-line-misc-info)
# (find-evariable 'mode-line-misc-info)

((which-function-mode (which-func-mode (which-func--use-mode-line ("" which-func-format " "))))
 (global-mode-string ("" global-mode-string)))








#####
#
# topos
# 2021jul05
#
#####

# «topos»  (to ".topos")
# https://github.com/b-mehta/topos
# (find-git-links "https://github.com/b-mehta/topos" "topos")
# (code-c-d "topos" "~/usrc/topos/")
# (find-toposfile "")
# (find-toposfile "README.md")
# (find-toposfile "src/")
# (find-toposfile "src/applications/")
# (find-toposfile "src/category/")



#####
#
# diagram-chasing
# 2021jul05
#
#####

# «diagram-chasing»  (to ".diagram-chasing")
# (find-books "__cats/__cats.el" "himmel")
# (find-himmeldiagchpage 19 "3.2. A formal proof of the four lemma")
# (find-himmeldiagchtext 19 "3.2. A formal proof of the four lemma")




#####
#
# prelude
# 2023jun29
#
#####

# «prelude»  (to ".prelude")
# (find-tpil4file "inductive_types.md" "prelude")
# (find-tpil4file "propositions_and_proofs.md" "Prelude.core")
# (find-lean4prefile "")
# (find-lean4prefile "")
# (find-lean4prefile "Init/")
# (find-lean4prefile "Init/Prelude.lean")
# (find-lean4prefile "Lean/")



#####
#
# rec_on
# 2023jul10
#
#####

# «rec_on»  (to ".rec_on")
# (find-tpinleanpage 89 "nat.rec_on")
# (find-tpinleantext 89 "nat.rec_on")
# (find-tpinleanpage 102 "weekday.rec_on (also generated automatically)")
# (find-tpinleantext 102 "weekday.rec_on (also generated automatically)")
# (find-tpinleanpage 103 "renaming option")
# (find-tpinleantext 103 "renaming option")

https://github.com/leanprover/theorem_proving_in_lean4/blob/master/inductive_types.md

inductive weekday : Type
| sunday : weekday
| monday : weekday
| tuesday : weekday
| wednesday : weekday
| thursday : weekday
| friday : weekday
| saturday : weekday

#check weekday.sunday
#check weekday.monday
#check weekday.rec
#check weekday.casesOn


weekday.casesOn.{u} {motive : weekday → Sort u}
  (t : weekday)
  (sunday : motive weekday.sunday)
  (monday : motive weekday.monday)
  (tuesday : motive weekday.tuesday)
  (wednesday : motive weekday.wednesday)
  (thursday : motive weekday.thursday)
  (friday : motive weekday.friday)
  (saturday : motive weekday.saturday) : motive t

weekday.rec.{u} {motive : weekday → Sort u}
  (sunday : motive weekday.sunday)
  (monday : motive weekday.monday)
  (tuesday : motive weekday.tuesday)
  (wednesday : motive weekday.wednesday)
  (thursday : motive weekday.thursday)
  (friday : motive weekday.friday)
  (saturday : motive weekday.saturday)
  (t : weekday) : motive t





@[reducible]

inductive mynat : Type
| zero : mynat
| succ : mynat → mynat

-- #check zero
#check mynat.zero

open mynat (renaming rec_on → rec_on)

def add (m n : mynat) : mynat :=
  mynat.rec_on n m (λ n add_m_n => succ add_m_n)

#check add
#check mynat
#check mynat.rec
#check mynat.rec_on

#check succ zero
#check add (succ zero) (succ (succ zero))

-- try it out
#reduce add (succ zero) (succ (succ zero))




#####
#
# alectryon
# 2024mar24
#
#####

# «alectryon»  (to ".alectryon")
# (to "mdbook")
# https://github.com/cpitclaudel/alectryon
# https://github.com/Kha/alectryon
# https://proofassistants.stackexchange.com/questions/62/is-there-software-for-interfacing-lean-code-with-latex
# https://leanprover-community.github.io/archive/stream/270676-lean4/topic/Literate.20programming.20in.20Lean4.20.2F.20Lean4.20.2B.20Org.20mode.html




#####
#
# nng4
# 2023jun27 / 2024jun03
#
#####

# «nng4»  (to ".nng4")
# https://github.com/leanprover-community/NNG4
# (find-git-links "https://github.com/leanprover-community/NNG4" "NNG4")
# (code-c-d "NNG4" "~/usrc/NNG4/")
# (find-NNG4sh "find * | sort")
# (find-NNG4file "")
# (find-NNG4file "README.md")
# (find-NNG4file "README.md" "https://adam.math.hhu.de")
# (find-NNG4file "Game.lean")
# (find-NNG4file "lakefile.lean")


# Old:
# https://github.com/PatrickMassot/NNG4




#####
#
# lean4game
# 2024jun03
#
#####

# «lean4game»  (to ".lean4game")
# https://github.com/leanprover-community/lean4game
# (find-git-links "https://github.com/leanprover-community/lean4game" "lean4game")
# (code-c-d "lean4game" "~/usrc/lean4game/")
# (find-lean4gamefile "")
# (find-lean4gamefile "README.md")
# (find-lean4gamefile "doc/")
# (find-lean4gamefile "server/")
# (find-lean4gamesh "find * | sort")





#####
#
# natural-number-game
# 2021oct06
#
#####

# «natural-number-game»  (to ".natural-number-game")
# https://www.ma.imperial.ac.uk/~buzzard/xena/natural_number_game/
# https://www.ma.imperial.ac.uk/~buzzard/xena/natural_number_game/FAQ.html
# https://www.ma.imperial.ac.uk/~buzzard/xena/natural_number_game/FAQ.html#sourcecode
# https://github.com/ImperialCollegeLondon/natural_number_game
# https://github.com/mpedramfar/Lean-game-maker

# (find-git-links "https://github.com/ImperialCollegeLondon/natural_number_game" "nng")
# (find-git-links "https://github.com/mpedramfar/Lean-game-maker" "lgm")
# (code-c-d "nng" "~/usrc/natural_number_game/")
# (code-c-d "lgm" "~/usrc/Lean-game-maker/")

# (find-nngfile "")
# (find-nngfile "docs/technical.md")
# (find-nngfile "docs/technical.md" "tactic monad")
# (find-nngfile "src/tactic/")
# (find-nngfile "src/tactic/modded.lean")
# (find-nngfile "src/game/")
# (find-nngfile "src/game/world2/")
# (find-nngfile "src/game/world2/level1.lean")

# (find-lgmfile "")

https://www.ma.imperial.ac.uk/~buzzard/xena/
https://www.youtube.com/watch?v=9V1Xo1n_3Qw LftCM2020: Natural number game - Kevin Buzzard
https://xenaproject.wordpress.com/2019/10/24/chalkdust-and-the-natural-number-game/
https://xenaproject.wordpress.com/2019/11/12/the-natural-number-game-an-update/




#####
#
# real-number-game
# 2021oct17
#
#####

# «real-number-game»  (to ".real-number-game")
# https://github.com/ImperialCollegeLondon/real-number-game
# (find-git-links "https://github.com/ImperialCollegeLondon/real-number-game" "rng")
# (code-c-d "rng" "~/usrc/real-number-game/")
# (find-rngfile "")



#####
#
# set-theory-game
# 2024may17
#
#####

# «set-theory-game»  (to ".set-theory-game")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Set.20theory.20game
# https://adam.math.hhu.de/
# https://adam.math.hhu.de/#/g/djvelleman/stg4




#####
#
# mathsinlean
# 2023jun24
#
#####

# «mathsinlean»  (to ".mathsinlean")
# «:leanmaths»                     (to ".:leanmaths")
# (find-angg ".emacs.lean.el" "ee-rstdoc-:leanmaths")
# (find-angg ".emacs.papers" "mathsinlean")
# https://leanprover-community.github.io/mathematics_in_lean/
# https://github.com/leanprover-community/mathematics_in_lean
# (find-wgetrecursive-links "https://leanprover-community.github.io/mathematics_in_lean/")
# https://github.com/avigad/mathematics_in_lean_source

# (find-git-links "https://github.com/leanprover-community/mathematics_in_lean" "mathsinlean")
# (code-c-d "mathsinlean" "~/bigsrc/mathematics_in_lean/")
# (find-mathsinleanfile "")
# (find-mathsinleanfile "lake-packages/")
# (find-mathsinleanfile "MIL/")
# (find-mathsinleanfile "MIL/C01_Introduction/")
# (find-mathsinleanfile "MIL/C01_Introduction/S02_Overview.lean")
# (find-mathsinleanpage)
# (find-mathsinleantext)
# (find-mathsinleanpage 5 "lake exe cache get")
# (find-mathsinleantext 5 "lake exe cache get")
# (find-mathsinleangrep "grep --color=auto -nRH --null -e constant *")

# (find-lean4mlifile "Mathlib/Util/AssertExists.lean" "elab \"assert_not_exists \"")

# file:///home/edrx/bigsrc/mathematics_in_lean/html/C01_Introduction.html





#####
#
# mathsinlean-build
# 2024may25
#
#####

# «mathsinlean-build»  (to ".mathsinlean-build")
# https://github.com/avigad/mathematics_in_lean_source
# (find-git-links "https://github.com/avigad/mathematics_in_lean_source" "mathsinleansrc")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/~.2F.2Eagda.2Fdefaults.20and.20~.2F.2Eagda.2Flibraries.2C.20but.20in.20Lean.3F
# (code-c-d "mathsinleansrc" "~/bigsrc/mathematics_in_lean_source/")
# (find-mathsinleansrcfile "")
# (find-mathsinleansrcfile "README.md")
# (find-mathsinleansrcfile "README.md" "lake exe cache get")
# (find-mathsinleansrcfile "lakefile.lean")
# (find-mathsinleansrcfile "lakefile.lean" "require mathlib from git")
# (find-mathsinleansrcsh "find * | sort")

* (eepitch-shell3)
* (eepitch-kill)
* (eepitch-shell3)
# (find-sh "du -ch ~/bigsrc/mathematics_in_lean/")

du -ch  ~/bigsrc/mathematics_in_lean_source/
rm -Rfv ~/bigsrc/mathematics_in_lean_source/
cd      ~/bigsrc/
git clone https://github.com/avigad/mathematics_in_lean_source
cd      ~/bigsrc/mathematics_in_lean_source/

find * | sort | tee .files0
lake exe cache get           |& tee olecg
find * | sort | tee .files1


Another basic question... now I have a full copy of mathlib4 in
~/bigsrc/mathlib4/, and I tried to run this:

rm -Rfv ~/bigsrc/mathematics_in_lean/
cd      ~/bigsrc/
git clone https://github.com/leanprover-community/mathematics_in_lean
cd      ~/bigsrc/mathematics_in_lean/
lake exe cache get

Apparently 1) this downloaded another full copy of mathlib4 in
~/bigsrc/mathematics_in_lean/lake-packages/mathlib/, and 2) if I
create a project and I put a like like this

require mathlib from git
"https://github.com/leanprover-community/mathlib4"@"master"

in its lakefile.lean it will also download another full copy of
mathlib4... is there a way to make these copies be shared?






# Error:

LSP :: Yasnippet is not installed, but `lsp-enable-snippet' is set to `t'. You must either install yasnippet, or disable snippet support.
LSP :: Connected to [lean4-lsp:187121/starting /home/edrx/bigsrc/mathematics_in_lean]. [2 times]
LSP :: Unable to autoconfigure company-mode. [2 times]
LSP :: lean4-lsp:187121 initialized successfully in folders: (/home/edrx/bigsrc/mathematics_in_lean)
LSP :: You can configure this warning with the `lsp-enable-file-watchers' and `lsp-file-watch-threshold' variables
LSP :: Unable to autoconfigure company-mode. [2 times]
info: [256/540] Building Aesop.Tree.UnsafeQueue
info: [315/794] Building Aesop.Search.Queue
info: [353/794] Building Mathlib.Data.ListM.Basic
info: [538/794] Building Mathlib.Algebra.Order.Group.Defs
error: external command `/home/edrx/.elan/toolchains/leanprover--lean4---nightly-2023-06-20/bin/lean` exited with code 139
`/home/edrx/.elan/toolchains/leanprover--lean4---nightly-2023-06-20/bin/lake print-paths Init Mathlib.Data.Nat.Basic Mathlib.Data.Nat.Parity Mathlib.Tactic` failed:

stderr:
info: [155/374] Building Qq.MetaM
info: [218/540] Building Std.Data.String.Lemmas
info: [256/540] Building Aesop.Tree.UnsafeQueue
info: [315/794] Building Aesop.Search.Queue
info: [353/794] Building Mathlib.Data.ListM.Basic
info: [538/794] Building Mathlib.Algebra.Order.Group.Defs
error: > LEAN_PATH=./lake-packages/proofwidgets/build/lib:./lake-packages/mathlib/build/lib:./build/lib:./lake-packages/Qq/build/lib:./lake-packages/aesop/build/lib:./lake-packages/std/build/lib LD_LIBRARY_PATH=./lake-packages/proofwidgets/build/lib:./lake-packages/mathlib/build/lib:./build/lib:./lake-packages/Qq/build/lib:./lake-packages/aesop/build/lib:./lake-packages/std/build/lib:./lake-packages/mathlib/build/lib /home/edrx/.elan/toolchains/leanprover--lean4---nightly-2023-06-20/bin/lean -DwarningAsError=true -Dpp.unicode.fun=true ./lake-packages/mathlib/././Mathlib/Algebra/Order/Group/Defs.lean -R ./lake-packages/mathlib/./. -o ./lake-packages/mathlib/build/lib/Mathlib/Algebra/Order/Group/Defs.olean -i ./lake-packages/mathlib/build/lib/Mathlib/Algebra/Order/Group/Defs.ilean -c ./lake-packages/mathlib/build/ir/Mathlib/Algebra/Order/Group/Defs.c
error: external command `/home/edrx/.elan/toolchains/leanprover--lean4---nightly-2023-06-20/bin/lean` exited with code 139
Mark set




#####
#
# mathsinlean-source
# 2024apr28
#
#####

# «mathsinlean-source»  (to ".mathsinlean-source")
# https://github.com/avigad/mathematics_in_lean_source
# https://leanprover-community.github.io/mathematics_in_lean/
# (find-git-links "https://github.com/avigad/mathematics_in_lean_source" "mathsinleansrc")
# (code-c-d "mathsinleansrc" "~/usrc/mathematics_in_lean_source/")
# (find-mathsinleansrcfile "")
# (find-mathsinleansrcfile "Makefile")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Recommended.20ways.20to.20convert.20Lean4.20code.20to.20LaTeX.3F/near/435827430
# (find-es "pygments" "mypygments.sh")




#####
#
# mathzoo
# 2023jun24
#
#####

# «mathzoo»  (to ".mathzoo")
# https://github.com/leanprover-community/mathzoo
# (code-c-d "mathzoo" "~/usrc/mathzoo/")
# (find-mathzoofile "")
# (find-mathzoosh "find * | sort")



#####
#
# mathlib
# 2023jun24
#
#####

# «mathlib»  (to ".mathlib")
# https://github.com/leanprover-community/mathlib
# (find-git-links "https://github.com/leanprover-community/mathlib" "mathlib")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv ~/bigsrc/mathlib/
cd      ~/bigsrc/
git clone https://github.com/leanprover-community/mathlib
cd      ~/bigsrc/mathlib/

# (code-c-d "mathlib" "~/bigsrc/mathlib/")
# (find-mathlibfile "")
# (find-mathlibfile "README.md")

# https://leanprover-community.github.io/install/linux.html




#####
#
# mathlib4
# 2023jun24
#
#####

# «mathlib4»  (to ".mathlib4")
# https://github.com/leanprover-community/mathlib4
# (find-git-links "https://github.com/leanprover-community/mathlib4" "mathlib4")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv ~/bigsrc/mathlib4/
cd      ~/bigsrc/
git clone https://github.com/leanprover-community/mathlib4
cd      ~/bigsrc/mathlib4/

cd      ~/bigsrc/mathlib4/
lake exe cache get

cd      ~/bigsrc/mathlib4/
git clean -dfx
git pull

elan self update
lake build   |& tee olb

# (code-c-d "mathlib4" "~/bigsrc/mathlib4/")
# (find-mathlib4file "")
# (find-mathlib4sh "find * | sort")
# (find-mathlib4file "README.md")
# (find-mathlib4file "README.md" "lean_exe")
# (find-mathlib4file "README.md" "elan self update")
# (find-mathlib4file "README.md" "lake build")
# (find-mathlib4file "" "lake")
# (find-mathlib4file "lake-manifest.json")
# (find-mathlib4file "lakefile.lean")
# (find-mathlib4file "olb")

# (find-mathlib4file "lakefile.lean" "package mathlib where")

# (find-mathlib4file "Mathlib/Data/Set/")
# (find-mathlib4file "Mathlib/Data/Set/Basic.lean")




#####
#
# mathlib4-greeting
# 2023jun26
#
#####

# «mathlib4-greeting»  (to ".mathlib4-greeting")
# (to "lake-new-greeting")
# (find-mathlib4file "README.md" "require mathlib from git")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv /tmp/gr/
mkdir   /tmp/gr/
cd      /tmp/gr/
lake new greeting
cd      /tmp/gr/greeting/

lake build
lake update
lake build

# (find-fline "/tmp/gr/greeting/")




#####
#
# mathlib-calculus
# 2022jul03
#
#####

# «mathlib-calculus»  (to ".mathlib-calculus")
# https://github.com/leanprover-community/mathlib
# https://leanprover-community.github.io/mathlib_docs/
# https://leanprover-community.github.io/mathlib_docs/analysis/calculus/deriv.html
# https://leanprover-community.github.io/get_started.html

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
# rm -Rfv ~/usrc/mathlib/
cd      ~/usrc/
git clone https://github.com/leanprover-community/mathlib
git clone git@github.com:leanprover-community/mathematics_in_lean.git
cd      ~/usrc/mathlib/
cd      ~/usrc/mathlib/


In a terminal, navigate to the folder where you want to put a copy of
the repository, and type git clone

git@github.com:leanprover-community/mathematics_in_lean.git

to fetch
it from github.

Navigate to mathematics_in_lean, and execute lake exe cache get to
fetch a compiled version of the library, mathlib.

Type code . to open the folder in VS Code. Alternatively, you can run
VS Code and choose Open Folder from the File menu. Be sure to open the
folder mathematics_in_lean, not any other folder.



;; <leanmathlib>
;; "The Lean Mathematical Library"
;; https://arxiv.org/abs/1910.09336
;; https://arxiv.org/pdf/1910.09336.pdf
(code-pdf-page "leanmathlib" "$S/https/arxiv.org/pdf/1910.09336.pdf")
(code-pdf-text "leanmathlib" "$S/https/arxiv.org/pdf/1910.09336.pdf")
;; (find-leanmathlibpage)
;; (find-leanmathlibtext)


# (find-anggsh "find . -mtime 0 | sort")
# (find-fline "~/.config/Code/")
# (find-fline "~/.local/pipx/logs/")
# (find-fline "~/.elan/")
# (find-fline "~/.local/pipx/")
# (find-fline "~/.mathlib/")
# (find-fline "~/.mathlib/url")
# (find-fline "~/.vscode/")



#####
#
# Server lean4-lsp:nnnn exited (...) Do you want to restart it?
# 2024may21
#
#####

# «lsp-server-exited-restart»  (to ".lsp-server-exited-restart")
# (find-elpafile "lsp-mode/lsp-mode.el" "Server %s exited")
# (find-lean4modefile "")

# Server lean4-lsp:nnnn exited (check corresponding stderr
# buffer for details). Do you want to restart it? (y or n)

LSP :: Connected to [lean4-lsp:250842/starting /tmp].
LSP :: Connected to [lean4-lsp:250961/starting /home/edrx/.elan/toolchains/leanprover--lean4---stable/src/lean].
LSP :: lean4-lsp:250842 initialized successfully in folders: (/tmp)
LSP :: lean4-lsp:250961 initialized successfully in folders: (/home/edrx/.elan/toolchains/leanprover--lean4---stable/src/lean)



#####
#
# lsp-yasnippet
# 2024may21
#
#####

# «lsp-yasnippet»  (to ".lsp-yasnippet")
LSP :: Yasnippet is not installed, but `lsp-enable-snippet' is set to `t'. You must either install yasnippet, or disable snippet support.
LSP :: Yasnippet is not installed, but `lsp-enable-snippet' is set to `t'. You must either install yasnippet, or disable snippet support.



#####
#
# tactics-list
# 2024may17
#
#####

# «tactics-list»  (to ".tactics-list")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Lean.204.20tactics.20list




#####
#
# tactics-in-ND
# 2021oct14
#
#####

# «tactics-in-ND»  (to ".tactics-in-ND")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Natural.20Deduction/near/257611457
# https://leanprover-community.github.io/mathlib_docs/tactic/explode.html#tactic.explode



#####
#
# vernacular
# 2021dec16
#
#####

# «vernacular»  (to ".vernacular")
# https://mathoverflow.net/questions/376839/what-makes-dependent-type-theory-more-suitable-than-set-theory-for-proof-assista
# https://www.youtube.com/watch?v=Dp-mQ3HxgDE#t=1h0m0s



#####
#
# fplean4
# 2023jun02
#
#####

# «fplean4»  (to ".fplean4")
# (find-angg ".emacs.lean.el" "ee-rstdoc-:fplean4")
# (find-angg ".emacs.papers" "fplean4")
# https://news.ycombinator.com/item?id=36107796 Functional Programming in Lean – a book on using Lean 4 to write programs (leanprover.github.io)
# https://leanprover.github.io/functional_programming_in_lean/
# https://leanprover.github.io/functional_programming_in_lean/print.html
# (find-fplean4page)
# (find-fplean4text)

https://lean-lang.org/functional_programming_in_lean/

https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/FPIL.20and.20TPIL.20with.20internal.20tables.20of.20contents.3F


# (find-wgetrecursive-links "https://lean-lang.org/functional_programming_in_lean/")
# (to "lean4-git")
# (find-code-rstdoc :lean4)





#####
#
# 3 essential commands and their syntax sugars
# 2024jun07
#
#####

# «3-essential»  (to ".3-essential")
# (to "elab_rules")
# (find-leanmetadoc  "main/02_overview#3-essential-commands-and-their-syntax-sugars")
# (find-leanmetadocr "main/02_overview.lean" "## 3 essential commands and their syntax sugars")
# (find-leanmetapage  9 "3 essential commands and their syntax sugars")
# (find-leanmetatext  9 "3 essential commands and their syntax sugars")
# (find-leanmetapage 11 "This image is not supposed")
# (find-leanmetatext 11 "This image is not supposed")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Elab Command

syntax (name := default_h) "#help" str : command
@[command_elab  default_h]
def helpElab : CommandElab := fun stx =>
  match stx with
  | `(#help "#explode") => logInfo "Message 1"
  | _ => Elab.throwUnsupportedSyntax

elab_rules : command
  | `(#help "#explode") => logInfo "Message 2"

elab "#help " x:str : command =>
  match x with
  | `("#explode")       => logInfo "Message 3"
  | _ => Elab.throwUnsupportedSyntax

#help "#explode"


syntax (name := shortcut_h) "#h" str : command

@[macro shortcut_h]
def helpMacro : Macro := fun stx =>
  match stx with
  | `(#h $x:str) => `(#help $x)
  | _ => Macro.throwUnsupported

macro_rules
  | `(#h $x:str) => `(#help $x)

macro "#h" x:str : command =>
  `(#help $x)

#h "#explode"

-- end



#####
#
# 3-essential-way-1
# 2024jun11
#
#####

# «3-essential-way-1»  (to ".3-essential-way-1")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Elab Command

syntax (name := default_h) "#help" str : command
@[command_elab  default_h]
def helpElab : CommandElab := fun stx =>
  match stx with
  | `(#help "#explode") => logInfo "Message 1"
  | _ => Elab.throwUnsupportedSyntax

syntax (name := shortcut_h) "#h" str : command
@[macro         shortcut_h]
def helpMacro : Macro := fun stx =>
  match stx with
  | `(#h $x:str) => `(#help $x)
  | _ => Macro.throwUnsupported

#help "#explode"
#h    "#explode"

-- end




#####
#
# 3-essential-way-2
# 2024jun11
#
#####

# «3-essential-way-2»  (to ".3-essential-way-2")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Elab Command

syntax "#help" str : command
elab_rules : command
  | `(#help "#explode") => logInfo "Message 2"

syntax "#h" str : command
macro_rules
  | `(#h $x:str) => `(#help $x)

#help "#explode"
#h    "#explode"

-- end




#####
#
# 3-essential-way-3
# 2024jun11
#
#####

# «3-essential-way-3»  (to ".3-essential-way-3")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Elab Command

elab "#help " x:str : command =>
  match x with
  | `("#explode")       => logInfo "Message 3"
  | _ => Elab.throwUnsupportedSyntax

macro "#h" x:str : command =>
  `(#help $x)

#help "#explode"
#h    "#explode"

elab "#minihelp " x:str : command => logInfo x
#minihelp "bla"

-- end






#####
#
# abbrev
# 2024may17
#
#####

# «abbrev»  (to ".abbrev")
# (find-lean4prefile "Init/Prelude.lean" "abbrev MacroM :=")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'abbrev' *")
# (find-fplean4page 17 "using abbrev instead of def")
# (find-fplean4text 17 "using abbrev instead of def")
# (find-fplean4page 17 "abbrev N : Type := Nat")
# (find-fplean4text 17 "abbrev N : Type := Nat")
# (find-lean4prefile "Lean/Parser/Command.lean" "def «abbrev\ »         := leading_parser")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

abbrev N  := Nat
abbrev Ns := List Nat

#check (2 : N)
#check (2 : N) + (3 : Int)
#eval  (2 : N) + (3 : Int)
#check [1,2]
#check ([1,2] : List Nat)
#check ([1,2] : Ns)         -- ?

-- end



#####
#
# addDecl
# 2024jun23
#
#####

# «addDecl»  (to ".addDecl")
# https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/name.20for.20syntax.20category.20of.20.60notation.60.2C.20.60namespace.60.2C.20.60def.60.2E.2E
# (find-lean-links "addDecl")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'addDecl' *")






#####
#
# anonymous
# 2024mar23
#
#####

# «anonymous»  (to ".anonymous")
# (to "partial-mutual")
# (find-tpil4page 29 "anonymous constructor")
# (find-tpil4text 29 "anonymous constructor")
# (find-tpil4page 33 "anonymous constructor")
# (find-tpil4text 33 "anonymous constructor")
# (find-fplean4page 202 "anonymous angle-bracket notation")
# (find-fplean4text 202 "anonymous angle-bracket notation")
# (find-tpil4doc  "propositions_and_proofs#conjunction")
# (find-tpil4docr "propositions_and_proofs" "### Conjunction")
# (find-tpil4docr "propositions_and_proofs" "anonymous constructor")
# (find-fplean4doc "functor-applicative-monad/inheritance")
# (find-fplean4doc "functor-applicative-monad/inheritance" "anonymous angle-bracket")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

structure  A where s : String deriving Repr
def   a1 : A := ⟨"foo"⟩
#eval a1
#eval a1.s

-- end




#####
#
# antiquotation
# 2024jun12
#
#####

# «antiquotation»  (to ".antiquotation")
# (to "match")
# (to "fun")
# (find-lean4prefile "Init/Prelude.lean" "an antiquotation `$id:ident`")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'antiquotation' *")
# (find-leanmetadoc  "main/06_macros#syntax-quotations")
# (find-leanmetadoc  "main/06_macros#the-basics")
# (find-leanmetadocr "main/06_macros" "### The basics")
# (find-leanmetapage 63 "Syntax Quotations")
# (find-leanmetatext 63 "Syntax Quotations")
# (find-leanmetapage 64 "If we use the antiquotation syntax")
# (find-leanmetatext 64 "If we use the antiquotation syntax")





#####
#
# Array
# 2024may31
#
#####

# «Array»  (to ".Array")
# (find-lean4doc "array")
# (find-lean4prefile "Init/Prelude.lean" "structure Array (α : Type u) where")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def a := [0, 1, 2]
def b := List.toArray a
def c := Array.toList b
#check b
#check c
#eval b
#eval c

-- end




#####
#
# assign
# 2024may28
#
#####

# «assign»  (to ".assign")
# (to "do-notation")
# (find-lean-links "assign")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'assign' *")
# (find-lean4prefile "Lean/Elab/Do.lean" "x := x + 1")
# (find-leanmetadoc  "main/04_metam#basic-operations")
# (find-leanmetadocr "main/04_metam" "### Basic Operations")
# (find-leanmetadocr "main/04_metam" "Metavariables are initially unassigned. To assign them, use")
# (find-fplean4doc "monad-transformers/do#mutable-variables")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Lean.Expr Lean.Meta

#eval show MetaM Unit from do
  -- Create two fresh metavariables of type `Nat`.
  let mvar1 ← mkFreshExprMVar (Expr.const ``Nat []) (userName := `mvar1)
  let mvar2 ← mkFreshExprMVar (Expr.const ``Nat []) (userName := `mvar2)
  -- Create a fresh metavariable of type `Nat → Nat`. The `mkArrow` function
  -- creates a function type.
  let mvar3 ← mkFreshExprMVar (← mkArrow (.const ``Nat []) (.const ``Nat []))
    (userName := `mvar3)

  -- Define a helper function that prints each metavariable.
  let printMVars : MetaM Unit := do
    IO.println s!"  meta1: {← instantiateMVars mvar1}"
    IO.println s!"  meta2: {← instantiateMVars mvar2}"
    IO.println s!"  meta3: {← instantiateMVars mvar3}"

  IO.println "Initially, all metavariables are unassigned:"
  printMVars

  -- Assign `mvar1 : Nat := ?mvar3 ?mvar2`.
  mvar1.mvarId!.assign (.app mvar3 mvar2)
  IO.println "After assigning mvar1:"
  printMVars

  -- Assign `mvar2 : Nat := 0`.
  mvar2.mvarId!.assign (.const ``Nat.zero [])
  IO.println "After assigning mvar2:"
  printMVars

  -- Assign `mvar3 : Nat → Nat := Nat.succ`.
  mvar3.mvarId!.assign (.const ``Nat.succ [])
  IO.println "After assigning mvar3:"
  printMVars
-- Initially, all metavariables are unassigned:
--   meta1: ?_uniq.1
--   meta2: ?_uniq.2
--   meta3: ?_uniq.3
-- After assigning mvar1:
--   meta1: ?_uniq.3 ?_uniq.2
--   meta2: ?_uniq.2
--   meta3: ?_uniq.3
-- After assigning mvar2:
--   meta1: ?_uniq.3 Nat.zero
--   meta2: Nat.zero
--   meta3: ?_uniq.3
-- After assigning mvar3:
--   meta1: Nat.succ Nat.zero
--   meta2: Nat.zero
--   meta3: Nat.succ

-- end





#####
#
# @[...]
# 2024may18
#
#####

# «attributes»  (to ".attributes")
# (find-lean-links "attribute")
# (find-leanmetadocrgrep "grep --color=auto -niRH --null -e 'attribute' *")
# (find-tpil4grep    "grep --color=auto -niRH --null -e 'attribute' *.md")
# (find-tpil4file "interacting_with_lean.md" "Attributes")
# (find-tpil4page  85 "6.4. Attributes")
# (find-tpil4text  85      "Attributes")
# (find-tpil4doc  "interacting_with_lean#attributes")
# (find-tpil4docr "interacting_with_lean" "Attributes")
# (find-lean4pregrep "grep --color=auto -niRH --null -e '\"@\\[\"' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'attributes' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'attributes' * | grep -a optional")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'elabDeclAttrs' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'mkDefViewOfDef' *")
# (find-lean4prefile "Init/Notation.lean" "`attr` is a builtin syntax category for attributes.")
# (find-lean4prefile "Init/Notation.lean" "def attr : Category := {}")
# (find-lean4prefile "Lean/Elab/Attributes.lean" "Format.bracket \"@[\"")
# (find-lean4prefile "Lean/Elab/Attributes.lean" "leading_parser \"@[\" >> sepBy1 attrInstance")
# (find-lean4prefile "Lean/Elab/Attributes.lean" "-- leading_parser \"@[\"")
# (find-lean4prefile "Lean/Elab/DeclModifiers.lean")
# (find-lean4prefile "Lean/Parser/Term.lean" "def attributes")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "@[builtin_command_parser] def «macro\ »")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "@[builtin_command_parser] def «elab_rules\ »")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "@[builtin_command_parser] def «elab\ »")
# (find-lean4prefile "Lean/Parser/Command.lean" "def declModifiers (inline : Bool) := leading_parser")
# (find-lean4prefile "Lean/Elab/DefView.lean" "leading_parser \"def \" >> declId >> optDeclSig")




#####
#
# axiom
# 2023jun24
#
#####

# «axiom»  (to ".axiom")
# (to "postulate")
# (find-lean-links "axiom")
# (find-tpil4doc  "propositions_and_proofs")
# (find-tpil4doc  "propositions_and_proofs#propositions-as-types")
# (find-tpil4docr "propositions_and_proofs" "Propositions as Types")
# (find-tpil4docr "propositions_and_proofs" "An \"axiom\" would be")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'axiom' *")
# (find-lean4file "doc/declarations.md" "axiom c : α")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"axiom \"' *")
# (find-lean4doc  "declarations")
# (find-lean4docr "declarations.md")
# (find-lean4doc "")
# (find-es "agda" "postulates")

# (find-tpil4page 26 "the axiom declaration")
# (find-tpil4text 26 "the axiom declaration")



#####
#
# batteries
# 2024jun12
#
#####

# «batteries»  (to ".batteries")
# https://github.com/leanprover-community/batteries
# (find-git-links "https://github.com/leanprover-community/batteries" "batteries")
# (code-c-d "batteries" "~/usrc/batteries/")
# (find-batteriessh "find * | sort")
# (find-batteriessh "find * .lake/ | sort")
# (find-batteriessh "find * .lake/ | sort | grep '\\.lean$'")
# (find-batteriesfile "")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd      ~/usrc/batteries/

lake -R -Kdoc=on update
lake -R -Kdoc=on build Batteries:docs
...
> ls build/doc/index.html
build/doc/index.html






#####
#
# builtin_initialize
# 2024may18
#
#####

# «builtin_initialize»  (to ".builtin_initialize")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'builtin_command' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'builtin_command_elab' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'builtin_command_parser' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'builtin_initialize' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'register' * | grep -ia attribute")
# (find-lean4prefile "Init.lean")
# (find-lean4prefile "Init/Prelude.lean")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "registerBuiltinParserAttribute `builtin_syntax_parser")

# (find-lean4file "")
# (find-lean4file ".files")
# (find-lean4sh "du -ch")



#####
#
# #check
# 2024may18
#
#####

# «check»  (to ".check")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '#check' *")
# (find-fplean4page 12 "#eval (1 + 2 : Nat)")
# (find-fplean4text 12 "#eval (1 + 2 : Nat)")
# (find-fplean4page 13 "#check (1 - 2 : Int)")
# (find-fplean4text 13 "#check (1 - 2 : Int)")
# (find-fplean4page 15 "#check add1")
# (find-fplean4text 15 "#check add1")
# (find-fplean4page 15 "#check (add1)")
# (find-fplean4text 15 "#check (add1)")
# (find-fplean4page 54 "#check fun (x : Int) => x + 1")
# (find-fplean4text 54 "#check fun (x : Int) => x + 1")
# (find-fplean4page 55 "(· + 1)")
# (find-fplean4text 55 "(· + 1)")
# (find-lean4file "doc/functions.md")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check  1
#check  1 : Int    -- bad
#check (1 : Int)   -- good
#check   Nat
#check   Nat -> Nat
#check ((Nat -> Nat) : Type)
#check ( Nat -> Nat  : Type)

#check   fun  x        => x + 1
#check   fun (x : Nat) => x + 1
#check ((fun (x : Nat) => x + 1) : (Nat -> Nat))
#check                   (· + 1)
#check                  ((· + 1) : (Nat -> Nat))

-- end




#####
#
# Checking Polymorphic Functions' Types
# 2024jun12
#
#####

# «check-polymorphic»  (to ".check-polymorphic")
# (find-fplean4doc  "type-classes/polymorphism#checking-polymorphic-functions-types")
# (find-fplean4docr "type-classes/polymorphism#checking-polymorphic-functions-types")
# (find-fplean4page 111 "Checking Polymorphic Functions' Types")
# (find-fplean4text 111 "Checking Polymorphic Functions' Types")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check (IO.println)
#check @IO.println
#check   do Lean.logInfo "a"
#check @(do Lean.logInfo "a")

-- end





#####
#
# class
# 2024may23
#
#####

# «class»  (to ".class")
# (to "typeclass-seach")
# (to "export")
# (to "extends")
# (find-fplean4doc "type-classes")
# (find-fplean4doc "type-classes/pos#classes-and-instances")
# (find-fplean4page 101 "Overloading and Type Classes")
# (find-fplean4text 101 "Overloading and Type Classes")
# (find-fplean4page 104 "Classes and Instances")
# (find-fplean4text 104 "Classes and Instances")
# (find-leanrefdoc "lean-lang.org/lean4/doc/typeclass#type-classes")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

class Foo (α : Type) where plic : α → String
class Bar (α : Type) where plic : α → String

instance : Foo String where plic := fun _ => "(str)"
instance : Foo Bool   where plic := fun _ => "(bool)"
instance : Bar String where plic := fun _ => "|str|"
instance : Bar Bool   where plic := fun _ => "|bool|"

#eval Foo.plic "a"
#eval Foo.plic true
#eval Bar.plic "a"
#eval Bar.plic true

-- export Foo (plic)
export Bar (plic)

#check plic
#eval  plic "a"
#eval  plic true

-- end





#####
#
# class-extends
# 2024may23
#
#####

# «class-extends»  (to ".class-extends")
# (find-fplean4page 217 "definition of Applicative that extends Functor")
# (find-fplean4text 217 "definition of Applicative that extends Functor")
# (find-fplean4page 218 "EXPR1 ={ REASON }= EXPR2")
# (find-fplean4text 218 "EXPR1 ={ REASON }= EXPR2")
# (find-lean-links "extends")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'extends' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" extends \"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'class Monad' * | grep -a extends")
# (find-lean4prefile "Init/Prelude.lean" "class Monad" "extends Applicative m, Bind m")
# (find-lean4prefile "Init/Prelude.lean" "class Applicative" "extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f")
# (find-lean4prefile "Init/Prelude.lean" "class Functor ")
# (find-lean4prefile "Init/Prelude.lean" "class Pure ")
# (find-lean4prefile "Init/Prelude.lean" "class Seq ")
# (find-lean4prefile "Init/Prelude.lean" "class SeqLeft ")
# (find-lean4prefile "Init/Prelude.lean" "class SeqRight ")
# (find-lean4prefile "Init/Prelude.lean" "class Bind ")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

instance : Monad List where
  pure := List.pure
  bind := List.bind

#check List.pure
#check List.bind
#check List.map
#check List.seq   -- err

-- end




#####
#
# command
# 2024may12
#
#####

# «command»  (to ".command")
# (to "checksyntax-test")
# (to "elab-term")
# (find-lean4prefile "Init/Notation.lean" "def command : Category := {}")
# (find-leanmetadoc  "main/01_intro#building-a-command")
# (find-leanmetapage 3 "Building a command")
# (find-leanmetatext 3 "Building a command")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean.Elab.Command
elab "#check_syntax " t:term : command => do Lean.logInfo m!"{t}"
#check_syntax 42 + "foo"

-- end





#####
#
# constant
# 2023jun24
#
#####

# «constant»  (to ".constant")
# (find-lean4pregrep "grep --color=auto -nRH --null -e constant *")
# (find-lean4grep "grep --color=auto -nRH --null -e constant doc/*")
# (find-lean4file "doc/funabst.md" "constant f : Nat → Nat")
# (find-lean4file "doc/typeobjs.md" "constant α : Type")
# (find-lean4file "doc/")
# (find-tpinleanpage 11 "constant m : nat")
# (find-tpinleantext 11 "constant m : nat")

# (find-tpinleanpage (+ 6 5) "2.1 Simple Type Theory")
# (find-tpinleantext (+ 6 5) "2.1 Simple Type Theory")
# (find-lean4file "doc/simptypes.md" "Simple Type Theory")
# (find-lean4file "doc/simptypes.md" "The ``constant`` command")

# (find-lean4file "doc/SUMMARY.md" "# Language Manual")
# (find-lean4file "doc/SUMMARY.md" "[Theorem Proving in Lean](./tpil.md)")
# (find-lean4docr "SUMMARY.md" "<!--   - [Function Abstraction and Evaluation](./funabst.md) -->")
# (find-lean4file "doc/tpil.md")

# (find-tpil4doc "introduction")
# (find-tpil4docrfile "")
# (find-tpil4docrgrep "grep --color=auto -nH --null -e constant *")

# (find-fline "~/bigsrc/lean4/doc/funabst.md")
~/bigsrc/lean4/doc/funabst.md
constant f : Nat → String
# (find-lean4docr "SUMMARY.md" "funabst.md")
# (find-lean4docr "funabst.md")




#####
#
# backtick
# 2024mar29
#
#####

# «backtick»  (to ".backtick")
# «double-backtick»  (to ".double-backtick")
# (to "exploring-data")
# (find-leanmetatext  1 "Constructing Expressions")
# (find-leanmetapage 18 "Constructing Expressions")
# (find-leanmetatext 18 "Constructing Expressions")
# (find-leanmetapage 54 "Constructing new Syntax")
# (find-leanmetatext 54 "Constructing new Syntax")
# (find-leanmetapage 55 "Matching on Syntax")
# (find-leanmetatext 55 "Matching on Syntax")
# (find-leanmetapage 69 "%$tk")
# (find-leanmetatext 69 "%$tk")

# (find-leanmetadoc  "main/03_expressions#constructing-expressions")
# (find-leanmetadocr "main/03_expressions" "## Constructing Expressions")
# (find-leanmetadoc  "main/05_syntax#constructing-new-syntax")
# (find-leanmetadocr "main/05_syntax" "### Constructing new `Syntax`")
# (find-leanmetadocr "main/05_syntax.lean" "is the syntax of `Nat.add 1 1`")
# (find-leanmetadoc  "main/05_syntax#matching-on-syntax")
# (find-leanmetadocr "main/05_syntax" "### Matching on `Syntax`")
# (find-leanmetadocr "main/05_syntax" "`(Nat.add $x $y)")
# (find-lean-links "backtick")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"`(\"' *")
# (find-angg "LEAN/syntax.lean" "mini-project")
# (find-lean4prefile "Init/Prelude.lean" "`Lean.Meta.whnf")
# (find-lean4prefile "Lean/Elab/Syntax.lean" "private def declareSyntaxCatQuotParser" "`(")
# (find-lean4prefile "Lean/Parser/Term.lean" "@[builtin_term_parser] def dynamicQuot" "`(")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean
open   Nat
def   z₁ := Expr.const  `zero []
#eval z₁ -- Lean.Expr.const `zero []
def   z₂ := Expr.const ``zero []
#eval z₂ -- Lean.Expr.const `Nat.zero []

#check   zero
#check  `zero
#check ``zero
#check  `(zero)

-- end



#####
#
# backtick-syntaxcat
# 2024jun08
#
#####

# «backtick-syntaxcat»  (to ".backtick-syntaxcat")
# (to "denoteArith")
# (to "info-scp-mainModule")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean

declare_syntax_cat syntaxA
declare_syntax_cat syntaxB

syntax num                  : syntaxA
syntax "[B: " syntaxA " :]" : syntaxB
syntax "[A: " syntaxB " :]" : syntaxA

#check `(             42)
#check `(syntaxA|     42)
#check `(syntaxB| [B: 42:])

-- end





#####
#
# Bind
# 2024may23
#
#####

# «Bind»  (to ".Bind")
# (to "do-notation")
# (find-es "lean" "instance-Monad-List")
# (find-lean-links ">>=")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '>>=' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" >>= \"' *")
# (find-lean4prefile "Init/Notation.lean" "infixl:55  \" >>= \" => Bind.bind")
# (find-lean4prefile "Init/Prelude.lean" "class Bind (m : Type u → Type v) where")
# (find-lean4prefile "Init/Prelude.lean" "export Bind (bind)")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def main2 : IO UInt32 := do
 IO.println "hello"
 IO.println "world"
 return 0

def main3 : IO UInt32 :=
  bind (IO.println "hello") (fun _ =>
  bind (IO.println "world") (fun _ =>
  pure 0))

#check            IO.println
#check            IO.println "hello"
#check Bind.bind (IO.println "hello")
#check Bind.bind
#print main2
set_option pp.notation false in
#print main2
#print bind
#print pure

#check (inferInstance : Bind IO)
#check (inferInstance : Pure IO)

-- end




#####
#
# binop%
# 2024jun12
#
#####

# «binop»  (to ".binop")
# (to "precedence")
# (find-lean4prefile "Init/Notation.lean" "macro_rules | `($x + $y)   => `(binop% HAdd.hAdd $x $y)")
# (find-lean4prefile "Lean/Elab/Extra.lean" "`binop% f a b` elaborates `f a b` as")




#####
#
# calc
# 2024apr06
#
#####

# «calc»  (to ".calc")
# https://leanprover-community.github.io/extras/calc.html
# (find-tpil4page 45 "Calculational Proofs")
# (find-tpil4text 45 "Calculational Proofs")
# (find-tpil4page 45 "with the keyword calc")
# (find-tpil4text 45 "with the keyword calc")
# (find-tpil4file "quantifiers_and_equality.md")
# (find-tpil4file "quantifiers_and_equality.md" "Calculational Proofs")
# (find-lean-links "calc")
# (find-lean-links "Calc")
# (find-lean4presh "find * | sort")
# (find-lean4presh "find * | sort | grep Calc")




#####
#
# def
# 2024mar09
#
#####

# «def»  (to ".def")
# (to "addDecl")
# (find-fplean4page 15 "def maximum (n : Nat) (k : Nat) : Nat :=")
# (find-fplean4text 15 "def maximum (n : Nat) (k : Nat) : Nat :=")
# (find-tpil4page 11 "Definitions")
# (find-tpil4text 11 "Definitions")
# (find-tpil4-links "Definitions")
# (find-tpil4file "dependent_type_theory.md" "## Definitions")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"def \"' *")
# (find-lean4prefile "Lean/Elab/DefView.lean" "def mkDefViewOfDef")
# (find-lean4prefile "Lean/Elab/DefView.lean" "-- leading_parser \"def \" >> declId >>")
# (find-lean4prefile "Lean/Elab/DefView.lean" "else if declKind == ``Parser.Command.def then")
# (find-lean4prefile "Lean/Elab/DeclModifiers.lean" "structure Modifiers where")
# (find-lean4prefile "Lean/Elab/DeclModifiers.lean" "attrs           : Array Attribute := #[]")

# (find-lean4pregrep "grep --color=auto -nRH --null -e 'invalid syntax node kind' *")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def add0                     : Nat := 4
def add1 (n : Nat)           : Nat := n + 1
def add2 (n : Nat) (m : Nat) : Nat := n + m
def add3 (n : Nat) (m : Nat) : Nat :=

#eval add0
#eval add1 7
#eval add2 3 4
#eval add3 3 4

def add4  (a b : Nat) : Nat := a+b
def add5 :       Nat  → Nat := id
def add6 : Nat → Nat  → Nat := fun a b => a+b
def add7 : (x : Nat) → Nat  → Nat := fun a b => a+b

-- end







#####
#
# #check
# 2024mar28
#
#####

# «check»  (to ".check")
# (to "check-fun")
# (to "scoped-syntax")
# (find-lean-links "check")
# (find-lean-links ">>")
# (find-fplean4page 13 "use #check instead of #eval")
# (find-fplean4text 13 "use #check instead of #eval")
# (find-fplean4page 51 "#check 14")
# (find-fplean4text 51 "#check 14")
# (find-fplean4page 52 "#check (14 : Int)")
# (find-fplean4text 52 "#check (14 : Int)")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'check' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '#check' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '<|>' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'namespace Command' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'builtin_command_parser' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'elaboration function for' *")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def check")
# (find-lean4prefile "Lean/Parser/Command.lean" "\"#check \" >> termParser")




#####
#
# #checksyntax
# 2024may15
#
#####

# «checksyntax»  (to ".checksyntax")
# (find-leanmetadoc  "main/05_syntax#free-form-syntax-declarations")
# (find-leanmetadocw "main/05_syntax#free-form-syntax-declarations")
# (find-leanmetadocr "main/05_syntax" "### Free form syntax declarations")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'elaboration function for' *")
# (find-lean4prefile "Lean/Elab/Command.lean" "elaboration function for")
# (find-lean4prefile "Lean/Elab/Term.lean" "elaboration function for")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/How.20do.20I.20write.20a.20.22.23check_syntax.22.3F/near/438919441

Hi all,

I'm taking far too long to do this myself, so I decided to ask...

In the section "Free form syntax declarations" of the metaprogramming
book there's an example - inside "namespace Playground2" - in which
the command "#check_failure ⊥ OR (⊤ AND ⊥)" fails with the error
"elaboration function for 'Playground2.term_OR_' has not been
implemented". I only found that error message in two places in the
source:

here in Lean/Elab/Command.lean, and
here in Lean/Elab/Term.lean,

but lots of things happen before that error message...

How do I write a variant of #check or #check_failure - let me call
that variant "#check_syntax" - that parses the rest of the line like
#check or #check_failure, i.e., like this,

@[builtin_command_parser] def check := leading_parser "#check " >> termParser

but that does not try to elaborate the result of "termParser"? I would
like it to just print the resulting Syntax object...

---

Neat! If I run this,

#check `(42 + "foo")

then the output is:

do
  let info ← Lean.MonadRef.mkInfoFromRefPos
  let scp ← Lean.getCurrMacroScope
  let mainModule ← Lean.getMainModule
  pure
      {
        raw :=
          Lean.Syntax.node3 info `term_+_ (Lean.Syntax.node1 info `num (Lean.Syntax.atom info "42"))
            (Lean.Syntax.atom info "+")
            (Lean.Syntax.node1 info `str (Lean.Syntax.atom info "\"foo\"")) } : ?m.233 (Lean.TSyntax `term) (lsp)

I would still like to learn how to write a new command that works as
the first half of #check, but that helps!



If anyone else is reading this, here is a version that is trivial to run:

import Lean.Elab.Command

namespace Playground2

scoped syntax "⊥" : term
scoped syntax "⊤" : term
scoped syntax:40 term " OR " term : term
scoped syntax:50 term " AND " term : term

elab "#check_syntax " t:term : command => do Lean.logInfo m!"{t}"
elab "#check_syntax " t:term : command => do Lean.logInfo m!"{repr t.raw}"

#check_syntax ⊥ OR (⊤ AND ⊥)

end Playground2

The definition of "#check_syntax" that holds is the last one - to
change its behavior, reorder the "elab" lines.




#####
#
# checksyntax-test
# 2024may16
#
#####

# «checksyntax-test»  (to ".checksyntax-test")
# (to "TSyntax")
# (to "command")
# (to "interpolatedStr")
# (to "mkSyntaxQuotation")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean.Elab.Command
elab "#check_syntax " t:term : command => do Lean.logInfo m!"{t}"
elab "#check_syntax " t:term : command => do Lean.logInfo m!"{repr t.raw}"
elab "#check_syntax " t:term : command => do Lean.logInfo (repr t.raw)
#check_syntax 42 + "foo"
#check `(42 + "foo")

-- end



#####
#
# coercion
# 2024may19
#
#####

# «coercion»  (to ".coercion")
# (to "heterogeneous")
# (to "structure")
# (find-fplean4doc "type-classes/pos#overloaded-addition")
# (find-fplean4doc "type-classes/coercion")
# (find-lean-links "instance : Coe")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance : Coe' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '@\\[coe\\]' *")
# (find-lean4prefile "Init/Coe.lean")
# (find-lean4prefile "Lean/Meta/CoeAttr.lean" "to delaborate coercion functions as `↑`")
# (find-lean4prefile "Init/Notation.lean" "syntax (name := Attr.coe) \"coe\" : attr")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check (2 : Nat) + (3 : Int)    -- ↑2 + 3 : Int

structure A where n : Nat deriving Repr
structure B where n : Nat deriving Repr
instance : Coe A B where coe a := ⟨a.n * 10⟩
#eval  (⟨4⟩ : A)
#eval  (⟨5⟩ : B)
#eval ((⟨6⟩ : A) : B)

-- end




#####
#
# CommandElabM
# 2024may18
#
#####

# «CommandElabM»  (to ".CommandElabM")
# (to "run_cmd")
# (find-lean-links "CommandElabM")
# (find-leanmetadocrgrep "grep --color=auto -nRH --null -e 'CommandElabM' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'CommandElabM' *")
# (find-lean4prefile "Init/Notation.lean" "#eval show CommandElabM Unit from do doSeq")
# (find-lean4prefile "Lean/Elab/Command.lean" "abbrev CommandElabM := CommandElabCoreM Exception")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean.Elab.Command
#check CommandElabM

-- end





#####
#
# company
# 2024may07
#
#####

# «company»  (to ".company")
# (find-es "emacs" "company")
# (find-companyfile "company-capf.el")



#####
#
# CoreM
# 2024may17
#
#####

# «CoreM»  (to ".CoreM")
# (find-leanmetadoc  "main/04_metam")
# (find-leanmetadocw "main/04_metam")
# (find-leanmetadocr "main/04_metam")
# (find-leanmetadocr "main/04_metam" "`CoreM` gives access to the *environment*")
# (find-lean4prefile "Lean/CoreM.lean" "structure Context where")
# (find-lean4prefile "Lean/CoreM.lean" "structure Context where" "currNamespace")
# (find-lean4prefile "Lean/CoreM.lean" "instance : MonadResolveName CoreM where")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'CoreM' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'getCurrNamespace' *")
# (find-lean4prefile "Init/Prelude.lean" "def getCurrNamespace")




#####
#
# dbg_trace
# 2024may27
#
#####

# «dbg_trace»  (to ".dbg_trace")
# (to "eldoc")
# (find-leanmetapage 14 "Printing Messages")
# (find-leanmetatext 14 "Printing Messages")
# (find-leanmetadoc  "main/02_overview#printing-messages")
# (find-leanmetadocr "main/02_overview" "### Printing Messages")
# (find-lean-links "dbg_trace")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'dbg_trace' *")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean

elab "traces" : tactic => do
  let array := List.replicate 2 (List.range 3)
  Lean.logInfo m!"logInfo: {array}"
  dbg_trace  f!"dbg_trace: {array}"

example : True := by -- `example` is underlined in blue, outputting:
                     -- dbg_trace: [[0, 1, 2], [0, 1, 2]]
  traces -- now `traces` is underlined in blue, outputting
         -- logInfo: [[0, 1, 2], [0, 1, 2]]
  trivial

-- end




#####
#
# declare_syntax_cat
# 2024jun08
#
#####

# «declare_syntax_cat»  (to ".declare_syntax_cat")
# (to "Lean.Parser.Category")
# (to "macro_rules")
# (to "TSyntax")
# (find-leanmetadoc  "main/01_intro#building-a-dsl-and-a-syntax-for-it")
# (find-leanmetadocr "main/01_intro" "### Building a DSL and a syntax for it")
# (find-leanmetadocr "main/01_intro" "declare_syntax_cat arith")
# (find-leanmetapage 5 "declare_syntax_cat")
# (find-leanmetatext 5 "declare_syntax_cat")
# (find-leanmetadoc  "main/05_syntax")
# (find-leanmetadocr "main/05_syntax" "you will have to use `` `(category| ...)``")
# (find-lean-links "declare_syntax_cat")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'declare_syntax_cat' *")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")


-- end





#####
#
# denoteArith
# 2024jun08
#
#####

# «denoteArith»  (to ".denoteArith")
# (to "backtick-syntaxcat")
# (find-leanmetadocr "main/05_syntax.lean#mini-project")
# (find-leanmetadocr "main/05_syntax.lean" "### Mini Project")
# (find-leanmetadocr "main/05_syntax.lean" "partial def denoteArith : TSyntax `arith → Nat")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean

declare_syntax_cat arith

syntax num : arith
syntax arith "-" arith : arith
syntax arith "+" arith : arith
syntax "(" arith ")" : arith

partial def denoteArith : TSyntax `arith → Nat
  | `(arith| $x:num) => x.getNat
  | `(arith| $x:arith + $y:arith) => denoteArith x + denoteArith y
  | `(arith| $x:arith - $y:arith) => denoteArith x - denoteArith y
  | `(arith| ($x:arith)) => denoteArith x
  | _ => 0

def test : Elab.TermElabM Nat := do
  let stx ← `(arith| (12 + 2) - 4)
  pure (denoteArith stx)

#eval test -- 10

-- end





#####
#
# deriving
# 2024may31
#
#####

# «deriving»  (to ".deriving")
# (to "synth")
# (find-lean-links "deriving")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'deriving' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'deriving instance' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'deriving instance Repr' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"deriving \"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'optDeriving' *")
# (find-lean4prefile "Lean/Elab/Deriving/Basic.lean" "@[builtin_command_elab «deriving»]")
# (find-lean4prefile "Lean/Elab/Deriving/Repr.lean")
# (find-lean4prefile "Lean/Parser/Command.lean" "def optDeriving      := leading_parser")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def «deriving»")
# (find-lean4prefile "Init/Meta.lean" "deriving instance Repr for Syntax")




#####
#
# discard
# 2024may12
#
#####

# «discard»  (to ".discard")
# (find-leanmetadoc  "main/01_intro#building-a-command")
# (find-leanmetadocr "main/01_intro" "### Building a command")
# (find-lean4prefile "Init/Control/Basic.lean" "def Functor.discard")



#####
#
# doc-comments
# 2024may29
#
#####

# «doc-comments»  (to ".doc-comments")
# (to "eldoc")
# (find-leanrefdoc "lexical_structure#doc-comments")
# (find-lean4prefile "Lean/Parser/Term.lean" "a \"documentation comment\" like `/-- foo -/`")




#####
#
# do-iteration
# 2024may24
#
#####

# «do-iteration»  (to ".do-iteration")
# (to "Id.run")
# (find-lean-links  "range")
# (find-lean4doc  "do#iteration")
# (find-lean4docr "do.md" "## Iteration")
# (find-lean4docr "do.md" "[:x] is notation for the range [0, x)")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\\[:' *")
# (find-lean4prefile "Init/Core.lean" "inductive DoResultPRBC ")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def sum (xs : Array Nat) : IO Nat := do
  let mut s := 0
  for x in xs do { IO.println s!"x:{x}"; s:=s+x }
  return s

def sum' (xs : Array Nat) : Nat := Id.run <| do
  let mut s := 0
  for x in xs do s:=s+x
  return s

def sumEven (xs : Array Nat) : IO Nat := do
  let mut s := 0
  for x in xs do if x%2==0 then { IO.println s!"x:{x}"; s:=s+x }
  return s

#eval sum     #[1, 2, 3]
#eval sum'    #[1, 2, 3]
#eval sumEven #[1, 2, 3, 6]

-- end




#####
#
# do notation
# 2024mar23
#
#####

# «do-notation»  (to ".do-notation")
# (find-es "lean" "instance-Monad-List")
# (to "runActions")
# (to "let-mut")
# (to "Monad")
# (to "Bind")
# (to "sleep1")
# (to "pp.notation")
# (find-lean4doc  "do")
# (find-lean4doc  "do#the-do-notation")
# (find-lean4docr "do.md" "# The `do` notation")
# (find-lean4docrfile "do.md")
# (find-fplean4page 66 "Combining IO Actions")
# (find-fplean4text 66 "Combining IO Actions")
# (find-fplean4page 67 "let bindings in do use a left arrow")
# (find-fplean4text 67 "let bindings in do use a left arrow")
# (find-fplean4page 85 "left arrow immediately" "under parentheses")
# (find-fplean4text 85 "left arrow immediately" "under parentheses")
# (find-fplean4page 85 "(← IO.getStdout)")
# (find-fplean4text 85 "(← IO.getStdout)")
# (find-fplean4page 90 "do Notation")
# (find-fplean4text 90 "do Notation")
# (find-fplean4doc "hello-world/running-a-program#combining-io-actions")
# (find-fplean4doc "monads/do")
# (find-fplean4doc "monad-transformers/do")
# (find-fplean4doc "monad-transformers/do#single-branched-if")
# (find-fplean4doc "monad-transformers/do#early-return")
# (find-fplean4doc "monad-transformers/do#loops")
# (find-fplean4doc "monad-transformers/do#stopping-iteration")
# (find-fplean4doc "monad-transformers/do#mutable-variables")
# (find-fplean4doc "monad-transformers/do#what-counts-as-a-do-block")
# (find-fplean4doc "monad-transformers/conveniences#infinite-loops")
# (find-fplean4doc "monad-transformers/conveniences#while-loops")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"do \"' *")
# (find-lean4prefile "Lean/Elab/Do.lean")
# (find-lean4prefile "Lean/Parser/Do.lean")
# (find-lean4prefile "Init/Prelude.lean" "the type `m Unit` represents an action")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

instance : Monad List where
  pure := List.pure
  bind := List.bind

def foo := do let a ← [0, 1]; let b ← [a+1, a+2]; return (a,b)

set_option pp.notation false in
#print foo

def main2 : IO UInt32 := do
 IO.println "hello"
 IO.println "world"
 return 0

def main3 : IO UInt32 :=
  bind (IO.println "hello") (fun _ =>
  bind (IO.println "world") (fun _ =>
  pure 0))

#check IO.println "hello"
#print main2
set_option pp.notation false in
#print main2
#print bind
#print pure

#check (inferInstance : Bind IO)
#check (inferInstance : Pure IO)

#check do return 42
#check do let _ := 42
#check do let _ ← IO.getStdin
#check do let _ ← IO.getStdin; let _ ← IO.getStdin
#check do let a ← IO.getStdin; let b ← IO.getStdin; return [a,b]

#check do
  let stdin <- IO.getStdin

-- end



#####
#
# " .. "
# 2024jun20
#
#####

# «dotdot»  (to ".dotdot")
# (find-lean4pregrep "grep --color=auto -nRH --null -e ' \\.\\. ' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e ' \\.\\. ' * | grep -a '{'")
# (find-lean4prefile "Lean/Meta/InferType.lean" "| .bvar .. ")
# (find-lean4prefile "Init/System/IO.lean" "| .ok { type := .symlink, .. } =>")
# (find-lean4prefile "Lean/Server/CodeActions/Attr.lean" "let { env, opts, .. } ← read")




#####
#
# eglot
# 2024jun20
#
#####

# «eglot»  (to ".eglot")
# https://codeberg.org/mekeor/nael
# https://github.com/bustercopley/lean4-mode




#####
#
# elab
# 2024mar30
#
#####

# «elab»  (to ".elab")
# (find-leanmetadoc  "main/01_intro#building-a-command")
# (find-leanmetadocw "main/01_intro#building-a-command")
# (find-leanmetadocr "main/01_intro" "elab \"#assertType \"")
# (find-leanmetadocr "main/01_intro" "inductive Arith : Type where")
# (find-leanmetadocrgrep "grep --color=auto -nH --null -e '^elab ' main/*")
# (find-lean4prefile "Init/Notation.lean" "`f $ x` means the same as the same as `f x`")
# (find-lean4prefile "Lean/Elab/SyntheticMVars.lean" "def synthesizeSyntheticMVarsNoPostponing")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

elab "#assertType " termStx:term " : " typeStx:term : command =>
  open Lean Lean.Elab Command Term in
  liftTermElabM
    try
      let tp ← elabType typeStx
      discard $ elabTermEnsuringType termStx tp
      synthesizeSyntheticMVarsNoPostponing
      logInfo "success"
    catch | _ => throwError "failure"

-- /-- info: success -/
-- #guard_msgs in --#
-- #assertType 5  : Nat

/-- error: failure -/
#guard_msgs in --#
#assertType [] : Nat

#check Lean.Elab.Command.liftTermElabM
#check Lean.Elab.Term.elabType
#check Lean.Elab.Term.elabTermEnsuringType
#check Functor.discard

-- end

‘
’: unknown constant 'Lean.Elab.Command.CommandElab'
‘
’: unknown constant 'Lean.Elab.throwUnsupportedSyntax'
Company: An error occurred in post-command
Company: frontend company-pseudo-tooltip-unless-just-one-frontend error "Company: backend company-capf error "Args out of range: #<buffer a.lean>, 754, 13" with args (match Unit)" on command post-command
Making completion list... [2 times]
Saving file /tmp/a.lean...
Wrote /tmp/a.lean
unexpected token '#assertType'; expected '#guard_msgs', 'abbrev', 'add_decl_doc', 'axiom', 'binder_predicate', 'builtin_initialize', 'builtin_simproc', 'builtin_simproc_decl', 'class', 'declare_config_elab', 'declare_simp_like_tactic', 'declare_syntax_cat', 'def', 'elab', 'elab_rules', 'example', 'inductive', 'infix', 'infixl', 'infixr', 'initialize', 'instance', 'macro', 'macro_rules', 'notation', 'opaque', 'postfix', 'prefix', 'register_builtin_option', 'register_label_attr', 'register_option', 'register_simp_attr', 'simproc', 'simproc_decl', 'structure', 'syntax', 'theorem' or 'unif_hint'


synthesizeSyntheticMVarsNoPostponing




#####
#
# elabIMP
# 2024jun19
#
#####

# «elabIMP»  (to ".elabIMP")
# (find-leanmetadoc  "main/08_dsls")
# (find-leanmetadocr "main/08_dsls")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean Elab Meta

inductive IMPLit
  | nat  : Nat  → IMPLit
  | bool : Bool → IMPLit
inductive IMPUnOp
  | not
inductive IMPBinOp
  | and | add | less
inductive IMPExpr
  | lit : IMPLit → IMPExpr
  | var : String → IMPExpr
  | un  : IMPUnOp → IMPExpr → IMPExpr
  | bin : IMPBinOp → IMPExpr → IMPExpr → IMPExpr
inductive IMPProgram
  | Skip   : IMPProgram
  | Assign : String → IMPExpr → IMPProgram
  | Seq    : IMPProgram → IMPProgram → IMPProgram
  | If     : IMPExpr → IMPProgram → IMPProgram → IMPProgram
  | While  : IMPExpr → IMPProgram → IMPProgram

declare_syntax_cat imp_lit
syntax num       : imp_lit
syntax "true"    : imp_lit
syntax "false"   : imp_lit

def elabIMPLit : Syntax → MetaM Expr
  | `(imp_lit| $n:num) => mkAppM ``IMPLit.nat  #[mkNatLit n.getNat]
  | `(imp_lit| true  ) => mkAppM ``IMPLit.bool #[.const ``Bool.true []]
  | `(imp_lit| false ) => mkAppM ``IMPLit.bool #[.const ``Bool.false []]
  | _ => throwUnsupportedSyntax

elab "test_elabIMPLit " l:imp_lit : term => elabIMPLit l

#reduce test_elabIMPLit 4     -- IMPLit.nat 4
#reduce test_elabIMPLit true  -- IMPLit.bool true
#reduce test_elabIMPLit false -- IMPLit.bool true

declare_syntax_cat imp_unop
syntax "not"     : imp_unop

def elabIMPUnOp : Syntax → MetaM Expr
  | `(imp_unop| not) => return .const ``IMPUnOp.not []
  | _ => throwUnsupportedSyntax

declare_syntax_cat imp_binop
syntax "+"       : imp_binop
syntax "and"     : imp_binop
syntax "<"       : imp_binop

def elabIMPBinOp : Syntax → MetaM Expr
  | `(imp_binop| +)   => return .const ``IMPBinOp.add []
  | `(imp_binop| and) => return .const ``IMPBinOp.and []
  | `(imp_binop| <)   => return .const ``IMPBinOp.less []
  | _ => throwUnsupportedSyntax

declare_syntax_cat                   imp_expr
syntax imp_lit                     : imp_expr
syntax ident                       : imp_expr
syntax imp_unop imp_expr           : imp_expr
syntax imp_expr imp_binop imp_expr : imp_expr

syntax "(" imp_expr ")" : imp_expr

partial def elabIMPExpr : Syntax → MetaM Expr
  | `(imp_expr| $l:imp_lit) => do
    let l ← elabIMPLit l
    mkAppM ``IMPExpr.lit #[l]
  -- `mkStrLit` creates an `Expr` from a `String`
  | `(imp_expr| $i:ident) => mkAppM ``IMPExpr.var #[mkStrLit i.getId.toString]
  | `(imp_expr| $b:imp_unop $e:imp_expr) => do
    let b ← elabIMPUnOp b
    let e ← elabIMPExpr e -- recurse!
    mkAppM ``IMPExpr.un #[b, e]
  | `(imp_expr| $l:imp_expr $b:imp_binop $r:imp_expr) => do
    let l ← elabIMPExpr l -- recurse!
    let r ← elabIMPExpr r -- recurse!
    let b ← elabIMPBinOp b
    mkAppM ``IMPExpr.bin #[b, l, r]
  | `(imp_expr| ($e:imp_expr)) => elabIMPExpr e
  | _ => throwUnsupportedSyntax

elab "test_elabIMPExpr " e:imp_expr : term => elabIMPExpr e

#reduce test_elabIMPExpr a
#reduce test_elabIMPExpr a + 5
#reduce test_elabIMPExpr 1 + true

declare_syntax_cat           imp_program
syntax "skip"              : imp_program
syntax ident ":=" imp_expr : imp_program

syntax imp_program ";;" imp_program : imp_program

syntax "if" imp_expr "then" imp_program "else" imp_program "fi" : imp_program
syntax "while" imp_expr "do" imp_program "od" : imp_program

partial def elabIMPProgram : Syntax → MetaM Expr
  | `(imp_program| skip) => return .const ``IMPProgram.Skip []
  | `(imp_program| $i:ident := $e:imp_expr) => do
    let i : Expr := mkStrLit i.getId.toString
    let e ← elabIMPExpr e
    mkAppM ``IMPProgram.Assign #[i, e]
  | `(imp_program| $p₁:imp_program ;; $p₂:imp_program) => do
    let p₁ ← elabIMPProgram p₁
    let p₂ ← elabIMPProgram p₂
    mkAppM ``IMPProgram.Seq #[p₁, p₂]
  | `(imp_program| if $e:imp_expr then $pT:imp_program else $pF:imp_program fi) => do
    let e ← elabIMPExpr e
    let pT ← elabIMPProgram pT
    let pF ← elabIMPProgram pF
    mkAppM ``IMPProgram.If #[e, pT, pF]
  | `(imp_program| while $e:imp_expr do $pT:imp_program od) => do
    let e ← elabIMPExpr e
    let pT ← elabIMPProgram pT
    mkAppM ``IMPProgram.While #[e, pT]
  | _ => throwUnsupportedSyntax

elab ">>" p:imp_program "<<" : term => elabIMPProgram p

#reduce >>
a := 5;;
if not a and 3 < 4 then
  c := 5
else
  a := a + 1
fi;;
b := 10
<<

-- end




#####
#
# elab_rules
# 2024jun08
#
#####

# «elab_rules»  (to ".elab_rules")
# (to "3-essential")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'elab_rules' *")
https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Widgets.20not.20displaying.20on.20some.20terms/near/434371640
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean

syntax "#help"   str : command
elab_rules           : command
  |   `(#help $s:str) => logInfo ("[h " ++ s ++ " h]")
#help         "BLAM"

syntax "[: "  term " :]" : term
elab_rules               : term
  |   `([: $t:term   :]) => do Elab.Term.elabTerm t none
#eval   [: 42        :]

-- end




#####
#
# elab-term
# 2024jun15
#
#####

# «elab-term»  (to ".elab-term")
# (to "command")
# (to "mapAddOneNil")
# (find-leanmetapage 11 "or any other syntax category")
# (find-leanmetatext 11 "or any other syntax category")
# (find-leanmetapage 11 "TermElab stands for Syntax → Option Expr →")
# (find-leanmetatext 11 "TermElab stands for Syntax → Option Expr →")
# (find-leanmetapage 20 "def mapAddOneNil : Expr :=")
# (find-leanmetatext 20 "def mapAddOneNil : Expr :=")
# (find-leanmetapage 20 "we can turn our Expr into a" "Lean term")
# (find-leanmetatext 20 "we can turn our Expr into a" "Lean term")
# (find-lean4prefile "Lean/Elab/Term.lean" "abbrev TermElab  := Syntax → Option Expr →")
# (find-lean4prefile "Lean/Elab/ElabRules.lean" "def elabElabRulesAux")
# (find-lean4prefile "Lean/Elab/ElabRules.lean" "def elabElabRulesAux" "if catName == `term")
# (find-lean4prefile "Lean/Elab/ElabRules.lean" "def elabElabRulesAux" "if catName == `command")
# (find-lean4prefile "Lean/Elab/ElabRules.lean" "def elabElabRulesAux" "if catName == `tactic")
# (find-lean4prefile "Lean/Elab/ElabRules.lean" "unsupported syntax category")
# (find-lean4gitgrep "grep --color=auto -nRH --null -e command_elab *")
# (find-lean4gitgrep "grep --color=auto -nRH --null -e term_elab *")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean

def nat1 : Expr := .const ``Nat   []
--                        ------  ------------
--                        : Name  : List Level
--                 ---------------------------
--                 : Expr

elab "nat2" : term => return (.const ``Nat   []          )
--                                   ------  ------------
--                                   : Name  : List Level
--                            ---------------------------
--                            : Expr
--                    -----------------------------------
--                    : m Expr
--                    -----------------------------------
--                    : TermElabM Expr

#check nat1
#check nat2
#check (3 : nat2)

#check TermElab

#check                            (.const ``Nat []  :           Expr)
elab "nat2"  : term    =>  return (.const ``Nat [])
elab "nat2"  : term    => (return (.const ``Nat []) : TermElabM Expr)
elab "say42" : command =>  logInfo "42"
elab "say42" : command => (logInfo "42" : CommandElabM Unit)
say42

declare_syntax_cat catB
elab "foo" : catB => 42  -- unsupported syntax category 'catB'

-- end









#####
#
# The type of the function in an elab
# 2024jun12
#
#####

# «elab-type»  (to ".elab-type")
# (to "repr-type")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Elab Command

elab "#withstring " x:str : command =>
  match x with
  | `("a") => logInfo x
  | `("b") => do { logInfo x; logInfo (repr x) }
  | `("c") => do { logInfo x; logInfo (repr x.raw) }
  | _ => Elab.throwUnsupportedSyntax

#withstring "a"
#withstring "b"
#withstring "c"

#check fun x => match x with | `("a") => 42 | _ => 42
#check fun x => match x with | _ => 42
#check fun x => match x with | _ => logInfo x
-- #check fun x =>
-- #check fun (x : Syntax) =>
#check fun (x : TSyntax `str) =>
  match x with
  | `("a") => logInfo x
  | `("b") => do { logInfo x; logInfo (repr x) }
  | `("c") => do { logInfo x; logInfo (repr x.raw) }
  | _ => Elab.throwUnsupportedSyntax

-- end




#####
#
# eldoc
# 2024may27
#
#####

# «eldoc»  (to ".eldoc")
# (to "doc-comments")
# (to "dbg_trace")
# (find-es "emacs" "eldoc-mode")





#####
#
# Environment
# 2024may18
#
#####

# «Environment»  (to ".Environment")
# (find-lean-links "Environment")
# (find-lean4prefile "Lean/CoreM.lean" "structure State where")



#####
#
# exceptions
# 2024may25
#
#####

# «exceptions»  (to ".exceptions")
# (to "try-catch")
# (find-lean-links "Except")
# (find-fplean4page 154 "Propagating Error Messages")
# (find-fplean4text 154 "Propagating Error Messages")
# (find-fplean4page 254 "Failure with OptionT")
# (find-fplean4text 254 "Failure with OptionT")
# (find-fplean4page 258 "Exceptions")
# (find-fplean4text 258 "Exceptions")
# (find-fplean4page 260 "Type Classes for Exceptions")
# (find-fplean4text 260 "Type Classes for Exceptions")
# (find-fplean4doc "monad-transformers/transformers#failure-with-optiont")
# (find-fplean4doc "monad-transformers/transformers#exceptions")
# (find-fplean4doc "monad-transformers/transformers#type-classes-for-exceptions")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Except' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'MonadExcept' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\\[MonadExcept ' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'class MonadExcept' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e ' Except ' *")
# (find-lean4prefile "Init/Prelude.lean" "inductive Except")
# (find-lean4prefile "Init/Prelude.lean" "An implementation of Haskell's [`MonadError`] class")
# (find-lean4prefile "Init/Prelude.lean" "class MonadExceptOf ")
# (find-lean4prefile "Init/Prelude.lean" "class MonadExcept ")
# (find-lean4prefile "Init/Control/Except.lean")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive Err where
  | divByZero
  | notANumber : String → Err

def asNumber [Monad m] [MonadExcept Err m] (s : String) : m Int :=
  match s.toInt? with
  | none => throw (.notANumber s)
  | some i => pure i

def divBackend [Monad m] [MonadExcept Err m] (n k : Int) : m Int :=
  if k == 0 then
    throw .divByZero
  else pure (n / k)

def divFrontend [Monad m] [MonadExcept Err m] (n k : String) : m String :=
  try
    pure (toString (← divBackend (← asNumber n) (← asNumber k)))
  catch
    | .divByZero => pure "Division by zero!"
    | .notANumber s => pure s!"Not a number: \"{s}\""

-- end






#####
#
# At sign
# 2024mar15
#
#####

# «explicit-arguments»  (to ".explicit-arguments")
# «implicit-arguments»  (to ".implicit-arguments")
# (find-lean-links "@")
# (find-tpil4doc  "dependent_type_theory")
# (find-tpil4doc  "dependent_type_theory#implicit-arguments")
# (find-tpil4docr "dependent_type_theory" "Implicit Arguments")
# (find-tpil4docr "dependent_type_theory" "@foo" "with all the arguments" "made explicit")
# (find-fplean4doc "getting-to-know/polymorphism")
# (find-fplean4doc "getting-to-know/polymorphism#implicit-arguments")
# (find-fplean4doc "getting-to-know/conveniences#automatic-implicit-arguments")
# (find-fplean4page 38 "Implicit Arguments")
# (find-fplean4text 38 "Implicit Arguments")
# (find-fplean4page 39 "#check List.length (α := Int)")
# (find-fplean4text 39 "#check List.length (α := Int)")
# (find-fplean4page 48 "Automatic Implicit Arguments")
# (find-fplean4text 48 "Automatic Implicit Arguments")
# (find-lean4pregrep "grep --color=auto -nRH --null -e ' @' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"@\"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '@' * | grep -ai explicit")
# (find-lean4prefile "Lean/Elab/App.lean" "`explicit = true` when notation `@` is used")
# (find-fplean4doc "type-classes/polymorphism#checking-polymorphic-functions-types")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check List.length
#check List.length (α := Int)
#check bind

instance : Monad List where
  pure := List.pure
  bind := List.bind

inductive A where |a1:A |a2:A deriving Repr
inductive B where |b1:B |b2:B deriving Repr
open A B

#check Bind.bind
#check bind
#check bind (m := List)
#check bind (m := List) (α := A)
#check bind (m := List) (α := A) (β := B)
#check bind (α := A) (m := List) (β := B)

def myfst : {A:Type} → {B:Type} → A×B → A := fun (a,b) => a

#eval myfst                          ("a",2)
#eval myfst (A := String) (B := Nat) ("a",2)
#eval myfst (A := String)            ("a",2)
#eval myfst               (B := Nat) ("a",2)

#check myfst
#check myfst (A := String)
#check myfst               (B := Nat)
#check myfst (A := String) (B := Nat)

-- end




#####
#
# exploring-data
# 2024may25
#
#####

# «exploring-data»  (to ".exploring-data")
# (to "extractFrom")
# (to "getCurrNamespace")
# (to "backtick")
# (to "match-bar")
# (find-fline "~/TH/eev-lean4.blogme" "exploring-data")
# (find-fline "~/LOGS/2024may25.haskell")
# (find-fline "~/LOGS/2024may25.haskell" "let (Just x) = Nothing in length [x, x, x]")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Tools.20for.20exploring.20data.20structures.3F
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

open Lean
#check Syntax
#check Syntax.mkNumLit
#check Syntax.mkNumLit "1"
#eval  Syntax.mkNumLit "1"
#check        mkAtom
#check        mkAtom "+"
#eval         mkAtom "+"
#check                           []
#check                          #[]
#check               `«term_+_»
#check        mkNode
#check        mkNode `«term_+_»
#check        mkNode `«term_+_» #[]
#eval         mkNode `«term_+_» #[]

def my1      := Syntax.mkNumLit "1"
def myadd    := mkIdent `Nat.add
def myplus   := `«term_+_»
def myadd11  := Syntax.mkApp myadd #[my1, my1]
def myplus11 := mkNode myplus #[my1, mkAtom "+", my1]

#eval  myadd11
#eval  Syntax.mkApp (mkIdent `Nat.add) #[Syntax.mkNumLit "1", Syntax.mkNumLit "1"]
#eval  mkNode `«term_+_» #[Syntax.mkNumLit "1", mkAtom "+", Syntax.mkNumLit "1"]
#eval  myplus11
#check myplus11
#check myplus11.raw
#eval  myplus11.raw

def Syntax.foo : Syntax → String
  | .missing              => "(m)"
  | .node  info kind args => "(n)"
  | .atom  info val       => "(a)"
  | .ident info rawVal val preresolved => "i"

def Name.foo : Name → String
  | .anonymous   => "(anon)"
  | .str pre str => str
  | .num pre i   => "num" ++ Name.foo pre

#eval            myplus
#eval            myplus11
#eval            myplus11.raw
#eval Syntax.foo myplus11.raw

#check Name
#check  myplus
#check Name.foo myplus
#eval  Name.foo myplus
#eval   myplus
#eval   myplus.str
#eval toString myplus
#eval repr myplus

macro "extractFrom " input:term " => " pat:term " => " result:term : term =>
  `(match ($input) with
     | some ($pat) => some ($result)
     | _ => none)

def a := some myadd11
#eval a
#check a
#check Syntax.node
def b := extractFrom a => Syntax.node info kind args => info  -- err

-- end



#####
#
# exploring-data-2
# 2024may26
#
#####

# «exploring-data-2»  (to ".exploring-data-2")
# (to "macro")
# (to "inductive-Option")
# (find-lean-links "matchAlt")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'matchAlt' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" matchAlt \"' *")
# (find-lean4prefile "Lean/Parser/Term.lean" "def matchAlt ")
# (find-lean4prefile "Lean/Parser/Term.lean" "def matchAlts ")
# (find-lean4prefile "Lean/Expr.lean" "def mvarId! : Expr → MVarId")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive N where
  | z         : N
  | s (n : N) : N
  deriving Repr

def c  := N.s (N.s N.z)

def b1 := match some c with
  | some (N.s x) => some x
  | _ => none

macro "extractFrom " input:term " => " pat:term " => " result:term : term =>
  `(match ($input) with
     | some ($pat) => some ($result)
     | _ => none)

def b2 := extractFrom some c => N.s x => x

#check b1
#eval  b1
#check b2
#eval  b2

#eval  extractFrom some (N.s N.z) => N.s x => x
#eval  extractFrom some      N.z  => N.s x => x

-- end









#####
#
# export
# 2024may23
#
#####

# «export»  (to ".export")
# (to "class")
# (find-lean-links "export")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'export' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"export \"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '«export»' *")
# (find-lean4prefile "Init/Prelude.lean" "export Decidable (isTrue isFalse decide)")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "@[builtin_command_elab «export»] def elabExport")
# (find-fplean4page 252 "doesn't need to be written with the type class name before it")
# (find-fplean4text 252 "doesn't need to be written with the type class name before it")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

class      ToLuaTree (α : Type) where toLuaTree : α → String
instance : ToLuaTree String     where toLuaTree str := q str
instance : ToLuaTree Int        where toLuaTree n   := toString n
instance : ToLuaTree Nat        where toLuaTree n   := toString n

#check ToLuaTree.toLuaTree
#check ToLuaTree.toLuaTree ("ab" : String)
#check ToLuaTree.toLuaTree  "ab"

export ToLuaTree (toLuaTree)

#check toLuaTree "ab"
#check toLuaTree 42

-- end




#####
#
# Expr
# 2024jun02
#
#####

# «Expr»  (to ".Expr")
# (find-lean4prefile "Lean/Expr.lean" "inductive Expr where")
# (find-lean4prefile "Lean/Expr.lean" "def ctorName : Expr → String")
# (find-lean4prefile "Lean/Expr.lean" "def ctorName : Expr → String" "| forallE .. =>")
# (find-lean4prefile "Lean/Expr.lean" "However, expressions sent to the kernel should not")
# (find-lean4prefile "Lean/Expr.lean" "contain metavariables.")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" \\.\\. \"' *")
# (find-leanmetadoc  "main/03_expressions")
# (find-leanmetadocr "main/03_expressions")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean
#check Expr

-- end





#####
#
# extends
# 2024jun01
#
#####

# «extends»  (to ".extends")
# (to "class")
# (to "Monad")
# (find-lean-links "extends")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

class Ca  (α : Type)              where ma : String
class Cb  (α : Type)              where mb : String
class Cbc (α : Type) extends Cb α where mc : String
inductive A where | a : A
instance : Ca  A where ma := "Ca.ma A"
instance : Cbc A where mb := "Cb.mb A"; mc := "Cbc.mc B"
#eval  Ca.ma  A
#eval  Cb.mb  A
#eval  Cbc.mc A

-- end






#####
#
# extern
# 2024mar23
#
#####

# «extern»  (to ".extern")
# (find-lean4prefile "Init/System/IO.lean" "@[extern \"lean_get_stdin\"] opaque getStdin")
# (find-lean4grep "grep --color=auto -nRH --null -e lean_get_stdin *")
# (find-lean4file "stage0/src/runtime/io.cpp" "lean_get_stdin")




#####
#
# extractFrom
# 2024may26
#
#####

# «extractFrom»  (to ".extractFrom")
# (to "exploring-data")
# (find-leanmetadoc  "main/06_macros#the-basics")
# (find-leanmetadocr "main/06_macros" "### The basics")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

macro "extractFrom " input:term " => " pat:term " => " result:term : term =>
  `(match ($input) with
     | some ($pat) => some ($result)
     | _ => none)

inductive N where
  | z         : N
  | s (n : N) : N
  deriving Repr

#eval                   (N.s N.z)
#eval              some (N.s N.z)
#eval  extractFrom some (N.s N.z) => N.s x => x
#eval  extractFrom some      N.z  => N.s x => x
#eval  extractFrom none           => N.s x => x

-- end






#####
#
# #eval
# 2024mar09
#
#####

# «eval»  (to ".eval")
# (find-fplean4page 12 "#eval (1 + 2 : Nat)")
# (find-fplean4text 12 "#eval (1 + 2 : Nat)")
# (find-fplean4page 88 "Running IO Actions With #eval")
# (find-fplean4text 88 "Running IO Actions With #eval")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'eval' *")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'eval' *")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'elabEval' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '#eval' *")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def eval" "\"#eval \"")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "@[builtin_command_elab «eval»,")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "unsafe def elabEvalUnsafe : CommandElab")
# (find-lean4docrgrep "grep --color=auto -nRH --null -e '#eval' *")




#####
#
# example
# 2024mar11
#
#####

# «example»  (to ".example")
# (to "metaprogramming")
# (find-angg ".emacs.papers" "tpil4" "The example command")
# (find-tpil4page 29 "The example command")
# (find-tpil4text 29 "The example command")
# (find-lean4pregrep "grep --color=auto -nRH --null -e example *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e Parser.Command *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e Lean.Parser *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e Lean.Parser.Command *")
# (find-lean4prefile "Lean/Elab/DefView.lean" "def | theorem | example | opaque | abbrev")
# (find-lean4prefile "Lean/Elab/DeclarationRange.lean" "Parser.Command.«example»")
# https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/name.20for.20syntax.20category.20of.20.60notation.60.2C.20.60namespace.60.2C.20.60def.60.2E.2E/near/446373495
# ^ "(It actually does create a declaration. It just then discards it via withoutModifyingEnv)."
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

variable (p q : Prop)

example (hp : p) (hq : q) : p ∧ q := And.intro hp hq

example (_ : Int)       := 42
example (_ : Int) : Int := 42

variable (P Q R : Prop)
variable {P Q R : Prop}
variable {p : P}
variable {q : Q}

example     (p : P) (q : Q) : P ∧ Q := And.intro p q
#check  fun (p : P) (q : Q)         => And.intro p q
#check (fun (p : P) (q : Q)         => And.intro p q : P → Q → P ∧ Q)

-- end




#####
#
# feline
# 2024jun20
#
#####

# «feline»  (to ".feline")
# (find-fplean4page 79 "Worked Example: cat")
# (find-fplean4text 79 "Worked Example: cat")
# (find-fplean4doc  "hello-world/cat")
# (find-fplean4docr "hello-world/cat")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def bufsize : USize := 20 * 1024

partial def dump (stream : IO.FS.Stream) : IO Unit := do
  let buf ← stream.read bufsize
  if buf.isEmpty then
    pure ()
  else
    let stdout ← IO.getStdout
    stdout.write buf
    dump stream

#check Stream

def fileStream (filename : System.FilePath) : IO (Option IO.FS.Stream) := do
  let fileExists ← filename.pathExists
  if not fileExists then
    let stderr ← IO.getStderr
    stderr.putStrLn s!"File not found: {filename}"
    pure none
  else
    let handle ← IO.FS.Handle.mk filename IO.FS.Mode.read
    pure (some (IO.FS.Stream.ofHandle handle))

def process (exitCode : UInt32) (args : List String) : IO UInt32 := do
  match args with
  | [] => pure exitCode
  | "-" :: args =>
    let stdin ← IO.getStdin
    dump stdin
    process exitCode args
  | filename :: args =>
    let stream ← fileStream ⟨filename⟩
    match stream with
    | none =>
      process 1 args
    | some stream =>
      dump stream
      process exitCode args

def main (args : List String) : IO UInt32 :=
  match args with
  | [] => process 0 ["-"]
  | _ =>  process 0 args


-- end






#####
#
# FFI
# 2024jun20
#
#####

# «FFI»  (to ".FFI")
# (find-sh "locate -i lean4/src | grep -i ffi")
# (find-lean4file "src/lake/examples/ffi/")
# (find-lean4file "src/Lean/Compiler/FFI.lean")
# (find-lean4page 121 "@[extern \"foreign_function\"]")
# (find-lean4text 121 "@[extern \"foreign_function\"]")
# (find-lean4page 153 "Foreign Function Interface")
# (find-lean4text 153 "Foreign Function Interface")
# (find-lean4doc "dev/ffi")



#####
#
# FilePath
# 2024jun15
#
#####

# «FilePath»  (to ".FilePath")
# (find-lean4prefile "Init/System/FilePath.lean")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
#check System.FilePath
#eval  (.mk "a" / "b.lean" : System.FilePath)

-- end





#####
#
# FirstTokens
# 2024may17
#
#####

# «FirstTokens»  (to ".FirstTokens")
# (to "leading_parser")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'firsttokens' *")
# (find-lean4prefile "Lean/Parser/Types.lean" "inductive FirstTokens where")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import    Lean.Parser.Term
import    Lean.Parser.Types
namespace Lean.Parser
def foo := leading_parser "foo "
#print   foo
#check   foo
#check   foo.info
#check   foo.info.firstTokens
#eval    foo.info.firstTokens
def a := foo.info.firstTokens
def b := FirstTokens.tokens ["$", "bar"]
#check a
#eval  a
#print a
#print b

namespace Types
#check FirstTokens
#check FirstTokens.epsilon
#eval  FirstTokens.epsilon
#check  ("a" : Token)
#check [("a" : Token), ("b" : Token)]
#check FirstTokens.tokens [("a" : Token), ("b" : Token)]
#check FirstTokens.tokens ["a", "b"]

#eval  foo.info.firstTokens

-- end






#####
#
# fun
# 2024mar22
#
#####

# «fun»  (to ".fun")
# (find-lean4doc  "functions")
# (find-lean4docr "functions.md")
# (find-tpil4doc)
# (find-tpil4doc  "dependent_type_theory")
# (find-tpil4doc  "dependent_type_theory#function-abstraction-and-evaluation")
# (find-tpil4docr "dependent_type_theory" "## Function Abstraction and Evaluation")
# (find-tpil4docr "dependent_type_theory" "`fun` (or `λ`)")
# (find-tpil4doc  "propositions_and_proofs")
# (find-tpil4doc  "propositions_and_proofs#propositions-as-types")
# (find-tpil4docr "propositions_and_proofs" "Propositions as Types")
# (find-tpil4docr "propositions_and_proofs" "``(fun x => t) s`` and ``t[s/x]``")
# (find-fplean4page 54 "Anonymous Functions")
# (find-fplean4text 54 "Anonymous Functions")
# (find-fplean4page 55 "centered dot")
# (find-fplean4text 55 "centered dot")
# (find-lean4prefile "Lean/Parser/Term.lean" "@[builtin_term_parser] def «fun»")
# (find-lean4prefile "Lean/Elab/Binders.lean" "@[builtin_term_elab «fun»]")
# (find-lean4prefile "Lean/Parser/Basic.lean" "def unicodeSymbol")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check fun  x        => x + 1
#check fun (x : Int) => x + 1
#check fun {α : Type} (x : α) => x

#check fun  x y                => x + y
#check fun (x : Int)  y        => x + y
#check fun (x : Int) (y : Int) => x + y
#check fun (x y : Int)         => x + y

#check (fun  x y               => x + y : Int → Int → Int)
#check  42
#check (42 : Int)

-- end




#####
#
# Functor
# 2024jun17
#
#####

# «Functor»  (to ".Functor")
# (to "LawfulFunctor")
# (find-lean4prefile "Init/Prelude.lean" "class Functor (f : Type u → Type v)")
# (find-books "__comp/__comp.el" "haskell-hutton")
# (find-books "__comp/__comp.el" "haskell-hutton" "182" "12.1     Functors")
# (find-lean-links "Functor")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Functor' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Functor' * | grep -a extends")
# (find-lean4pregrep "grep --color=auto -nRHw --null -e 'Functor' * | grep -a instance")

class Functor (f : Type → Type) : Type where map : {α β : Type} → (α → β) → f α → f β




#####
#
# getCurrNamespace
# 2024may18
#
#####

# «getCurrNamespace»  (to ".getCurrNamespace")
# (to "where")
# (to "run_cmd")
# (to "exploring-data")
# (find-lean-links "getCurrNamespace")
# (find-lean4prefile "Init/Prelude.lean" "def getCurrNamespace : MacroM Name := do")
# (find-THfile "eev-lean4.blogme" "getCurrNamespace")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
namespace Foo
run_cmd Lean.logInfo (← Lean.getCurrNamespace)

-- end



#####
#
# #guard_msgs
# 2024jun02
#
#####

# «guard_msgs»  (to ".guard_msgs")
# (find-lean4prefile "Lean/Elab/GuardMsgs.lean" "`#guard_msgs` command for testing commands")
# (find-leanmetadoc  "main/01_intro#building-a-command")
# (find-leanmetadocr "main/01_intro" "### Building a command")
# (find-leanmetadocr "main/01_intro" "### Building a command" "#guard_msgs")




#####
#
# guillemets
# 2024mar23
#
#####

# «guillemets»  (to ".guillemets")
# (find-fplean4page 76 "guillemets around a name")
# (find-fplean4text 76 "guillemets around a name")
# (find-lean4prefile "Lean/Parser/Extra.lean" "disallowed characters in identifiers")



#####
#
# HashMap
# 2024jun13
#
#####

# «HashMap»  (to ".HashMap")
# (find-lean4presh "find * | sort")
# (find-lean4presh "find * | sort | grep -i hash")
# (find-lean4presh "find * | sort | grep -i hash | grep build")
# (find-lean4presh "find * | sort | grep -i hash | grep -v build")
# (find-lean4prefile "Lean/Data/HashMap.lean")
# (find-lean4prefile "Lean/Data/HashMap.lean" "def ofList (l : List (α × β)) : HashMap α β :=")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/How.20to.20use.20a.20hashmap.3F
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
/-!
A very quick tutorial for using `HashMap`s
-/

open Lean

/-- using `HashMap.empty` and `HashMap.insert` -/
def myHM : HashMap Nat String := HashMap.empty
  |>.insert 1 "one"
  |>.insert 2 "two"
  |>.insert 3 "three"

--  the above is just for "clean" formatting: you could also write
--  `def myHM1 : HashMap Nat String := ((HashMap.empty.insert 1 "one").insert 2 "two").insert 3 "three"`

-- Now also `HashMap.find?` and `HashMap.contains`
#eval myHM.find? 1  -- `some "one"`
#eval myHM.find? 4  -- `none`
#eval myHM.contains 1  -- `true`
#eval myHM.contains 4  -- `false`

-- to print a HashMap, convert it to a `List` or an `Array`
#eval IO.println myHM.toArray -- #[(1, one), (2, two), (3, three)]
#eval IO.println myHM.toList  -- [(3, three), (2, two), (1, one)]

-- end



import Lean.Data.HashMap
open Lean.HashMap

def a := [("one", 1), ("two", 2)]
#check a
#eval ofList a   -- err





#####
#
# have
# 2024apr30
#
#####

# «have»  (to ".have")
# (find-lean-links "have")
# (find-angg ".emacs.papers" "tpil4")
# (find-tpil4file "propositions_and_proofs.md" "the ``have`` construct")
# (find-tpil4page  33 "3.4. Introducing Auxiliary Subgoals")
# (find-tpil4text  33      "Introducing Auxiliary Subgoals")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'have' *")
# (find-lean4prefile "Lean/Elab/Do.lean" "def getDoHaveVars (doHave : Syntax)")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

variable (P Q : Prop)

example (paq : P ∧ Q) : Q ∧ P :=
  have p : P := paq.left
  have q : Q := paq.right
  show Q ∧ P from And.intro q p

-- end





#####
#
# heterogeneous
# 2024may19
#
#####

# «heterogeneous»  (to ".heterogeneous")
# (to "coercion")
# (find-lean4pregrep "grep --color=auto -nRH --null -e Nat * | grep -a Int")
# (find-lean4pregrep "grep --color=auto -nRH --null -e Nat * | grep -a Int | grep -a Coe")
# (find-lean4pregrep "grep --color=auto -nRH --null -e ofNat *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" + \"' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'HAdd' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'hAdd' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'heterogeneous' *")
# (find-lean4prefile "Init/Notation.lean" "@[inherit_doc] infixl:65 \" + \"   => HAdd.hAdd")
# (find-lean4prefile "Init/Prelude.lean" "heterogeneous addition")
# (find-lean4prefile "Init/Prelude.lean" "instance [Add α] : HAdd α α α where")
# (find-lean4prefile "Init/Prelude.lean" "class OfNat (α : Type u) (_ : Nat) where")
# (find-lean4prefile "Init/Coe.lean" "# Coercion")
# (find-lean4prefile "Init/Coe.lean" "instance : Coe Nat Int := ⟨Int.ofNat⟩")
# (find-fplean4page 105 "Overloaded Addition")
# (find-fplean4text 105 "Overloaded Addition")
# (find-fplean4doc "type-classes/pos#overloaded-addition")
# (find-fplean4doc "type-classes/coercion")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check (2 : Nat) + (3 : Int)    -- ↑2 + 3 : Int

-- end




#####
#
# Id.run
# 2024may21
#
#####

# «Id.run»  (to ".Id.run")
# (to "Monad-S")
# (to "run_cmd")
# (to "show-from-do")
# (to "do-for-in")
# invalid `do` notation, expected type is not a monad application
# You can use the `do` notation in pure code by writing `Id.run do`
# instead of `do`, where `Id` is the identity monad. (lsp)

# (find-fplean4doc "monads/class#the-identity-monad")

# (find-lean-links "Id.run")
# (find-lean4prefile "Lean/Elab/Do.lean" "`do` notation in pure code by writing `Id.run do`")
# (find-lean4prefile "Init/Control/Id.lean" "protected def run (x : Id α) : α := x")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Id.run' *")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check                      do return 42
#check show Nat from        do return 42  -- err
#check               Id.run do return 42
#check show Nat from Id.run do return 42

instance : Monad List  where
  pure := List.pure
  bind := List.bind

#check show List Nat from                  [2, 3]
#check show List Nat from        do return [2, 3]  -- err
#check show List Nat from Id.run do return [2, 3]

-- end



#####
#
# if-let
# 2024may25
#
#####

# «if-let»  (to ".if-let")
# (find-fplean4page 57 "if let")
# (find-fplean4text 57 "if let")
# (find-fplean4page 271 "Single-Branched if")
# (find-fplean4text 271 "Single-Branched if")
# (find-fplean4doc "getting-to-know/conveniences#if-let")
# (find-fplean4doc "monad-transformers/do#single-branched-if")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive B where    -- binary tree
  | n (n : Nat)       : B
  | b (l : B) (r : B) : B

def foo (b : B) : Option Nat :=
  if let B.b bl _ := b then
    if let B.b _ blr := bl then
      if let B.n blrn := blr then
        some blrn
      else none
    else none
  else none

#check     B.b (.b (.n 1) (.n 2)) (.n 3)
#eval foo (B.b (.b (.n 1) (.n 2)) (.n 3))

-- end




#####
#
# import
# 2024mar31
#
#####

# «import»  (to ".import")
# (to "lake-current-directory")
# (to "namespace")
# (to "modules")
# (find-lean-links "import")
# (find-fplean4page 76 "The import line")
# (find-fplean4text 76 "The import line")
# (find-fplean4page 77 "Libraries and Imports")
# (find-fplean4text 77 "Libraries and Imports")
# (find-fplean4page 77 "decoupled from the namespace hierarchy")
# (find-fplean4text 77 "decoupled from the namespace hierarchy")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'import' *")
# (find-leanrefdoc "using_lean#import-resolution")
# (find-fplean4doc "hello-world/starting-a-project")
# (find-fplean4doc "hello-world/starting-a-project#first-steps")
# (find-fplean4doc "hello-world/starting-a-project#lakefiles")
# (find-fplean4doc "hello-world/starting-a-project#libraries-and-imports")
# (find-fplean4doc "hello-world/starting-a-project#libraries-and-imports" "decoupled")



#####
#
# import-problem
# 2024jun09
#
#####

# «import-problem»  (to ".import-problem")
# (find-TH "eev-lean4" "import")
# (to "lake-env")
# (to "server")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Need.20help.20to.20debug.20an.20import.20-.20and.20maybe.20a.20lakefile

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv /tmp/import-test/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv /tmp/import-test/
mkdir   /tmp/import-test/
cd      /tmp/import-test/

cat > A.lean <<'%%%'
  def a := "42"
  #eval a
%%%
cat > B.lean <<'%%%'
  -- (lsp-describe-session)
  import A
  #eval a
  def main : IO Unit := IO.println s!"Hello {a}"
%%%
cat > lakefile.lean <<'%%%'
  import Lake
  open   Lake DSL
  package A
  @[default_target] lean_lib A
  @[default_target] lean_exe b { root := `B } 
%%%

 lake build            ;# ok
.lake/build/bin/b      ;# ok
lean A.lean            ;# ok
lean B.lean            ;# unknown package 'A'
lake env lean B.lean   ;# ok
lake env

find * .lake/ | sort

# (find-fline "/tmp/import-test/")
# (find-fline "/tmp/import-test/A.lean")
# (find-fline "/tmp/import-test/B.lean")

# (code-c-d "importtest" "/tmp/import-test/")
# (find-importtestfile "")
# (find-importtestfile "A.lean")
# (find-importtestfile "B.lean")
# (find-importtestsh "find * .lake/ | sort")







#####
#
# indentation
# 2024mar09
#
#####

# «indentation»  (to ".indentation")
# (to "let")
# (find-fplean4-links "semicolon")
# (find-fplean4page 88 "This version uses only whitespace-sensitive layout")
# (find-fplean4text 88 "This version uses only whitespace-sensitive layout")

# (find-fplean4doc  "getting-to-know/conveniences#local-definitions")
# (find-fplean4docr "getting-to-know/conveniences" "## Local Definitions")
# (find-fplean4docr "getting-to-know/conveniences" "## Local Definitions" "semicolon")

# (find-fplean4page 87 "Flexible Layouts for do")
# (find-fplean4text 87 "Flexible Layouts for do")
# (find-fplean4page 87 "all of the following programs are equivalent")
# (find-fplean4text 87 "all of the following programs are equivalent")
# (find-fplean4doc  "hello-world/conveniences#flexible-layouts-for-do")
# (find-fplean4docr "hello-world/conveniences" "## Flexible Layouts for `do`")
# (find-fplean4docr "hello-world/conveniences" "## Flexible Layouts for `do`" "semicolon")
# (find-fplean4docr "hello-world/conveniences" "all of the following programs are equivalent")
# (find-fplean4file "examples/Examples/Cat.lean" "book declaration {{{ helloOne }}}")





#####
#
# inductive
# 2024mar23
#
#####

# «inductive»  (to ".inductive")
# (to "mutual")
# (find-fplean4page 26 "inductive Bool where")
# (find-fplean4text 26 "inductive Bool where")
# (find-fplean4page 58 "Positional Structure Arguments")
# (find-fplean4text 58 "Positional Structure Arguments")
# (find-fplean4page 129 "inductive BinTree")
# (find-fplean4text 129 "inductive BinTree")
# (find-lean4prefile "Lean/Elab/Declaration.lean" "leading_parser \"inductive \"")
# (find-lean4presh "find * | sort | grep -i inductive")




#####
#
# inductive-Arith
# 2024may12
#
#####

# «inductive-Arith»  (to ".inductive-Arith")
# (to "p123456")
# (find-leanmetadoc  "main/01_intro#building-a-dsl-and-a-syntax-for-it")
# (find-leanmetadocr "main/01_intro" "### Building a DSL and a syntax for it")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "declare_syntax_cat")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "def catBehavior :=")
# (find-lean4prefile "Lean/Elab/Syntax.lean"     "@[builtin_command_elab «syntax»]")
# (find-lean4prefile "Lean/Elab/MacroRules.lean" "@[builtin_command_elab «macro_rules»]")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "@[builtin_command_parser] def «syntax»")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "@[builtin_command_parser] def «macro_rules»")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive Arith : Type where
  | add : Arith → Arith → Arith -- e + f
  | mul : Arith → Arith → Arith -- e * f
  | nat : Nat → Arith           -- constant
  | var : String → Arith        -- variable

declare_syntax_cat arith
syntax num                        : arith -- nat for Arith.nat
syntax str                        : arith -- strings for Arith.var
syntax:50 arith:50 " + " arith:51 : arith -- Arith.add
syntax:60 arith:60 " * " arith:61 : arith -- Arith.mul
syntax " ( " arith " ) "          : arith -- bracketed expressions

syntax " <. " arith " .> " : term

macro_rules
  | `(<. $s:str .>)              => `(Arith.var $s)
  | `(<. $num:num .>)            => `(Arith.nat $num)
  | `(<. $x:arith + $y:arith .>) => `(Arith.add <. $x .> <. $y .>)
  | `(<. $x:arith * $y:arith .>) => `(Arith.mul <. $x .> <. $y .>)
  | `(<. ( $x ) .>)              => `( <. $x .> )

#check <. "x" * "y" .>
#check <. "x" + "y" .>
#check <. "x" + 20 .>
#check <. "x" + "y" * "z" .> -- precedence
#check <. "x" * "y" + "z" .> -- precedence
#check <. ("x" + "y") * "z" .> -- brackets

-- end


#check <. ("x"      +       20) *    "z"   .>
           --------   --------    --------
              str        num        str
           --------   --------    
           arith:50   arith:51
           -------------------
                arith:50
          ---------------------
                arith          
          ---------------------   --------
                arith:60          arith:61
           -------------------------------
                      arith:60
       --------------------------------------
                    term



#####
#
# inductive-Expr
# 2024may12
#
#####

# «inductive-Expr»  (to ".inductive-Expr")
# (find-leanmetadoc  "main/03_expressions")
# (find-leanmetadocr "main/03_expressions")
# https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Creating.20Expr.20objects




#####
#
# inductive-List
# 2024may13
#
#####

# «inductive-List»  (to ".inductive-List")
# (find-fplean4page 37 "inductive List")
# (find-fplean4text 37 "inductive List")
# (find-lean4prefile "Init/Prelude.lean" "inductive List")
# (find-lean4prefile "Init/Data/List/Basic.lean" "syntax \"[\"")
# (find-lean4prefile "Init/Notation.lean" "@[inherit_doc] infixr:67 \" :: \" => List.cons")



#####
#
# inductive-N
# 2024may30
#
#####

# «inductive-N»  (to ".inductive-N")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive N where
  | z         : N
  | s (n : N) : N
  deriving Repr

def   ssz_a  := N.s (N.s N.z)
#eval ssz_a

open N
def   ssz_b := s (s z)
#eval ssz_b

-- end




#####
#
# inductive-Nat
# 2024may13
#
#####

# «inductive-Nat»    (to ".inductive-Nat")
# «inductive-myNat»  (to ".inductive-myNat")
# (find-fplean4page 27 "inductive Nat")
# (find-fplean4text 27 "inductive Nat")
# (find-fplean4page 31 "def plus")
# (find-fplean4text 31 "def plus")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive myNat where
  | zero             : myNat
  | succ (n : myNat) : myNat

def my1 := myNat.succ myNat.zero

def my23 := match my1 with
  | myNat.zero   => 2
  | myNat.succ _ => 3

def myIncomplete := match my1 with
  | myNat.zero   => 42

-- end





#####
#
# inductive-Option
# 2024may15
#
#####

# «inductive-Option»  (to ".inductive-Option")
# (find-fplean4page 40 "inductive Option")
# (find-fplean4text 40 "inductive Option")
# (find-fplean4page 40 "def List.head?")
# (find-fplean4text 40 "def List.head?")
# (find-fplean4doc "getting-to-know/polymorphism#more-built-in-datatypes")
# (find-fplean4doc "getting-to-know/polymorphism#option")
# (find-fplean4doc "monads/arithmetic#evaluating-expressions")
# (find-lean4prefile "Init/Prelude.lean" "inductive Option ")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check List.head?

def List.myhead? {α : Type} (xs : List α) : Option α :=
  match xs with
  | [] => none
  | y :: _ => some y

#eval [].myhead?
#eval [].myhead? (α := Int)
#eval ([] : List Int).myhead?

-- end





#####
#
# inductive-Syntax
# 2024may15
#
#####

# «inductive-Syntax»  (to ".inductive-Syntax")
# (find-lean-links "Syntax")
# (find-leanmetadocrfile "main/01_intro.lean" "Concrete Syntax Tree, Lean's `Syntax` type")
# (find-leanmetadocrgrep "grep --color=auto -nRH --null -e 'Syntax' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Syntax' *")
# (find-lean4pregrep "grep --color=auto -nRHw --null -e 'Syntax' *")
# (find-lean4prefile "Lean/Syntax.lean")
# (find-lean4prefile "Init/Prelude.lean" "inductive Syntax where")
# (find-lean4prefile "Init/Prelude.lean" "inductive SourceInfo where")
# (find-leanmetadoc  "extra/03_pretty-printing")
# (find-leanmetatext 1 "let stx : Syntax")
# (find-leanmetapage 47 "let stx : Syntax")
# (find-leanmetatext 47 "let stx : Syntax")
# (find-leanmetapage 54 "Operating on Syntax")
# (find-leanmetatext 54 "Operating on Syntax")
# (find-leanmetapage 55 "Matching on Syntax")
# (find-leanmetatext 55 "Matching on Syntax")
# (find-leanmetadoc  "main/04_metam#exercises" "let stx : Syntax")
# (find-leanmetadocr "main/04_metam#exercises" "let stx : Syntax")
# (find-leanmetadoc  "main/05_syntax")
# (find-leanmetadoc  "main/05_syntax#operating-on-syntax")
# (find-leanmetadocr "main/05_syntax" "## Operating on Syntax")
# (find-leanmetadoc  "main/05_syntax#matching-on-syntax")
# (find-leanmetadocr "main/05_syntax" "### Matching on `Syntax`")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

-- end



#####
#
# inferInstance
# 2024may23
#
#####

# «inferInstance»  (to ".inferInstance")
# (to "Inhabited")
# (find-lean4prefile "Init/Prelude.lean" "#check (inferInstance : Inhabited Nat)")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check (inferInstance : Inhabited Nat) -- Inhabited Nat
def foo : Inhabited (Nat × Nat) := inferInstance
example : foo.default = (default, default) := rfl

-- end



#####
#
# inferType
# 2024jun12
#
#####

# «inferType»  (to ".inferType")
# (to "runTermElabM")
# (to "repr-type")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Is.20there.20a.20variant.20of.20repr.20that.20.22prints.20the.20type.22.3F
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean

open Lean Elab Command Meta

elab "#my_check " t:term : command => do
  runTermElabM fun _ => do -- go into term elaboration mode after processing any `variables` commands
    let e ← Term.elabTermAndSynthesize t none -- elaborate `t` and run all elaboration tasks to completion
    let eTy ← inferType e --  compute the type of `e`
    logInfo m!"{e} : {eTy}" -- log a MessageData with `e` and `eTy` embedded into it

#my_check "s"
-- "s" : String

-- end






#####
#
# infix
# 2024mar11
#
#####

# «infix»   (to ".infix")
# «infixl»  (to ".infixl")
# «infixr»  (to ".infixr")
# (find-fplean4page 153 "Infix Operators")
# (find-fplean4text 153 "Infix Operators")
# (find-fplean4page 153 "infixl:55 \" ~~> \" => andThen")
# (find-fplean4text 153 "infixl:55 \" ~~> \" => andThen")

# (find-leanmetadocr "main/05_syntax" "infixl:60 \" ⊕ \" => fun l r => (!l && r) || (l && !r)")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive myNat where
  | zero             : myNat
  | succ (n : myNat) : myNat

def my1 := myNat.succ myNat.zero

def my23 := match my1 with
  | myNat.zero   => 2
  | myNat.succ _ => 3

def myIncomplete := match my1 with
  | myNat.zero   => 42

-- end



#####
#
# info-scp-mainModule
# 2024jun08
#
#####

# «info-scp-mainModule»  (to ".info-scp-mainModule")
# (to "mkSyntaxQuotation")
# (to "backtick-syntaxcat")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
#check Lean.Elab.Term.Quotation.mkSyntaxQuotation
open   Lean.Elab.Term.Quotation
#check mkSyntaxQuotation

#check mkSyntaxQuotation
#check  `(42 + "foo")
#check (`(42 + "foo") : Lean.MacroM                  (Lean.TSyntax `term))

-- end






#####
#
# Inhabited
# 2024may23
#
#####

# «Inhabited»  (to ".Inhabited")
# (to "inferInstance")
# (find-lean4page 83 "inhabited and non empty")
# (find-lean4text 83 "inhabited and non empty")
# (find-lean4prefile "Init/Prelude.lean" "class Inhabited (α : Sort u) where")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Inhabited' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'inhabited and' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance : Inhabited' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'deriving Inhabited' *")
# (find-lean4prefile "Lean/Elab/PreDefinition/MkInhabitant.lean" "inhabited and non empty")

failed to compile partial definition 'toLTree_Syntax', failed to show
that type is inhabited and non empty




#####
#
# initialize
# 2024may29
#
#####

# «initialize»  (to ".initialize")
# (to "lake-new-greeting")
# (find-lean-links "initialize")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'initialize' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'initialize' * | grep -aw initialize")
# (find-lean4prefile "Lean/Elab/Declaration.lean" "@[builtin_macro Lean.Parser.Command.«initialize»]")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def «initialize» :=")
# (find-lean4prefile "Lean/Environment.lean" "are declared using the `initialize` command")





#####
#
# instance
# 2024mar14
#
#####

# «instance»  (to ".instance")
# (to "class")
# (to "Repr")
# (to "instance-Monad-List")
# (find-fplean4doc  "index")
# (find-fplean4doc "type-classes/pos#classes-and-instances")
# (find-fplean4doc "type-classes/pos#classes-and-instances")
# (find-fplean4page 104 "Classes and Instances")
# (find-fplean4text 104 "Classes and Instances")
# (find-fplean4page 104 "instance : Plus Nat where")
# (find-fplean4text 104 "instance : Plus Nat where")

# (find-tpil4doc  "type_classes")
# (find-tpil4docr "type_classes")
# (find-tpil4doc  "type_classes#chaining-instances")
# (find-tpil4docr "type_classes" "## Chaining Instances")
# (find-tpil4page 157 "Type Classes")
# (find-tpil4text 157 "Type Classes")
# (find-tpil4page 160 "Chaining Instances")
# (find-tpil4text 160 "Chaining Instances")

# (find-lean4doc  "typeclass")
# (find-lean4docr "typeclass.md")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance \\[' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance :' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance' * | grep -a Repr")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance' * | grep -a Command")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Command.instance' *")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def declaration :=")
# (find-lean4prefile "Lean/Parser/Command.lean" "def «instance\ »       := leading_parser")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

-- end





#####
#
# instance-implicits
# 2024jun12
#
#####

# «instance-implicits»  (to ".instance-implicits")
# (to "Options")
# (find-fplean4page 112 "in square brackets are called instance implicits")
# (find-fplean4text 112 "in square brackets are called instance implicits")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'instance' * | grep -ai implicit")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'instance \\[' *")
# (find-lean4prefile "Lean/Log.lean" "variable [Monad m] [MonadLog m] [AddMessageContext m]")
# (find-lean4prefile "Lean/PrettyPrinter/Delaborator/Options.lean" "pp.instances")
# (find-lean4prefile "Init/Control/State.lean" "instance [Alternative m] : Alternative (StateT σ m) wh")
# (find-lean4prefile "Lean/Parser/Term.lean" "An instance binder `[A]` or `[x : A]`")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def foo1 [Monad m] [MonadState σ m] (a : Nat) : m Nat := show m Nat from do return a
def foo2 [Monad m] [MonadState σ m] (a : Nat) : m Nat :=                 do return a

def foo3 [i1 : Monad m] [i2 : MonadState σ m] (a : Nat) : m Nat := do
  let xxxxxxxx := 42
  let b ← get
  -- let c ← bind
--return _
  return a

#check foo1
#check foo2

-- end
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean
#check logInfo
#check logInfo "a"

set_option pp.all true  in
#check logInfo "a"
set_option pp.all false in
#check logInfo "a"
set_option pp.beta true  in
#check logInfo "a"
set_option pp.beta false in
#check logInfo "a"
set_option pp.coercions true  in
#check logInfo "a"
set_option pp.coercions false in
#check logInfo "a"
set_option pp.deepTerms true  in
#check logInfo "a"
set_option pp.deepTerms false in
#check logInfo "a"
set_option pp.deepTerms.threshold true  in
#check logInfo "a"
set_option pp.deepTerms.threshold false in
#check logInfo "a"
set_option pp.explicit true  in
#check logInfo "a"
set_option pp.explicit false in
#check logInfo "a"
set_option pp.fullNames true  in
#check logInfo "a"
set_option pp.fullNames false in
#check logInfo "a"
set_option pp.funBinderTypes true  in
#check logInfo "a"
set_option pp.funBinderTypes false in
#check logInfo "a"
set_option pp.instanceTypes true  in
#check logInfo "a"
set_option pp.instanceTypes false in
#check logInfo "a"
set_option pp.instances true  in
#check logInfo "a"
set_option pp.instances false in
#check logInfo "a"
set_option pp.instantiateMVars true  in
#check logInfo "a"
set_option pp.instantiateMVars false in
#check logInfo "a"
set_option pp.letVarTypes true  in
#check logInfo "a"
set_option pp.letVarTypes false in
#check logInfo "a"
set_option pp.match true  in
#check logInfo "a"
set_option pp.match false in
#check logInfo "a"
set_option pp.motives.all true  in
#check logInfo "a"
set_option pp.motives.all false in
#check logInfo "a"
set_option pp.motives.nonConst true  in
#check logInfo "a"
set_option pp.motives.nonConst false in
#check logInfo "a"
set_option pp.motives.pi true  in
#check logInfo "a"
set_option pp.motives.pi false in
#check logInfo "a"
set_option pp.natLit true  in
#check logInfo "a"
set_option pp.natLit false in
#check logInfo "a"
set_option pp.notation true  in
#check logInfo "a"
set_option pp.notation false in
#check logInfo "a"
set_option pp.numericTypes true  in
#check logInfo "a"
set_option pp.numericTypes false in
#check logInfo "a"
set_option pp.piBinderTypes true  in
#check logInfo "a"
set_option pp.piBinderTypes false in
#check logInfo "a"
set_option pp.privateNames true  in
#check logInfo "a"
set_option pp.privateNames false in
#check logInfo "a"
set_option pp.proofs true  in
#check logInfo "a"
set_option pp.proofs false in
#check logInfo "a"
set_option pp.proofs.threshold true  in
#check logInfo "a"
set_option pp.proofs.threshold false in
#check logInfo "a"
set_option pp.proofs.withType true  in
#check logInfo "a"
set_option pp.proofs.withType false in
#check logInfo "a"
set_option pp.safeShadowing true  in
#check logInfo "a"
set_option pp.safeShadowing false in
#check logInfo "a"
set_option pp.structureInstanceTypes true  in
#check logInfo "a"
set_option pp.structureInstanceTypes false in
#check logInfo "a"
set_option pp.structureInstances true  in
#check logInfo "a"
set_option pp.structureInstances false in
#check logInfo "a"
set_option pp.structureProjections true  in
#check logInfo "a"
set_option pp.structureProjections false in
#check logInfo "a"
set_option pp.tagAppFns true  in
#check logInfo "a"
set_option pp.tagAppFns false in
#check logInfo "a"
set_option pp.unicode.fun true  in
#check logInfo "a"
set_option pp.unicode.fun false in
#check logInfo "a"
set_option pp.universes true  in
#check logInfo "a"
set_option pp.universes false in
#check logInfo "a"

-- end





#####
#
# instance : Monad List
# 2024may18
#
#####

# «instance-Monad-List»  (to ".instance-Monad-List")
# (to "instance")
# (2024tinsp 2 "instance-Monad-List")
# (2024tinsa   "instance-Monad-List")
# (find-es "haskell" "list-comprehensions")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance' * | grep -a Monad")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance' * | grep -a List")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'instance' * | grep -a Monad | grep -a List")
# (find-lean4doc  "monads/monads.lean#example-using-list")
# (find-lean4docr "monads/monads.lean" "## Example using List")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

instance : Monad List where
  pure := List.pure
  bind := List.bind

inductive A where |a1:A |a2:A deriving Repr
inductive B where |b1:B |b2:B deriving Repr
open A B
#eval do let a←[a1,a2]; let b←[b1,b2]; return (a,b)
#eval bind [a1,a2]  fun a   => bind [b1,b2]  fun b   => pure (a  ,b  )
--         --------     ---         --------     ---          --- ---
--         : List A     : A         : List B     : B          : A : B
--                                                           ---------
--                                                           : A×B
--                                                      --------------
--                                                      : List A×B
--                                           --------------------------
--                                           : B → List A×B
--                             ----------------------------------------
--                             : List A×B
--                  ---------------------------------------------------
--                  : A → List A×B
--     ----------------------------------------------------------------
--     : List A×B

def foo := do let a←[a1,a2]; let b←[b1,b2]; return (a,b)

set_option pp.all true in
#print foo

#check Bind.bind

-- end





#####
#
# interpolatedStr
# 2024may16
#
#####

# «interpolatedStr»  (to ".interpolatedStr")
# (to "string-interpolation")
# (to "checksyntax-test")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 's!' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'interpolatedStr' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'syntax:max \"s!\"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'syntax:max \"m!\"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'syntax:max \"f!\"' *")
# (find-lean4prefile "Lean/Parser/StrInterpolation.lean")
# (find-lean4prefile "Init/Data/ToString/Macro.lean" "syntax:max \"s!\"")
# (find-lean4prefile "Lean/Message.lean"             "syntax:max \"m!\"")
# (find-lean4prefile "Init/Data/Format/Macro.lean"   "syntax:max \"f!\"")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check m!"a{2+3}b"
#check s!"a{2+3}b"
#check f!"a{2+3}b"

-- end






#####
#
# IO
# 2024jun01
#
#####

# «IO»  (to ".IO")
# (find-lean4prefile "Init/System/IO.lean" "abbrev IO : Type → Type := EIO Error")
# (find-lean4prefile "Init/System/IO.lean" "def EIO (ε : Type) : Type → Type :=")
# (find-lean4prefile "Init/System/IO.lean" "instance : Monad (EIO ε) :=")
# (find-lean4prefile "Init/System/IOError.lean" "inductive IO.Error where")
# (find-lean4prefile "Init/Prelude.lean" "def EStateM (ε σ α : Type u) := σ → Result ε σ α")




#####
#
# IO.print and IO.println
# 2024mar22
#
#####

# «IO.print»    (to ".IO.print")
# «IO.println»  (to ".IO.println")
# (find-fplean4page 106 "IO.println")
# (find-fplean4text 106 "IO.println")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#eval               "foo\nbar\n"
#eval    IO.println "foo\nbar\n"
#eval do IO.println "foo\nbar\n"
#eval do IO.print   "foo\nbar\n"

-- end






#####
#
# IO.Process.output
# 2024mar11
#
#####

# «IO.Process.output»  (to ".IO.Process.output")
# (find-angg "LEAN/luatree2.lean")
# (find-lean4prefile "Init/System/IO.lean" "Run process to completion")
# (find-lean4prefile "lake/Lake/Config/InstallPath.lean")
# (find-lean4prefile "lake/Lake/Config/InstallPath.lean" "let out ← IO.Process.output {")
# (find-lean4pregrep "grep --color=auto -nirH --null -e pipe *")
# (find-lean4pregrep "grep --color=auto -nirH --null -e Process.Stdio.piped *")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/IO.2EProcess.2Eoutput.20with.20stdin.20being.20a.20string.3F

# (find-lean4prefile "")


IO.Process.output with stdin being a string?

Hi all! How do I tell IO.Process.output to run with its stdin being
(piped from) a string? Or, more precisely: how do I write a function
"tac" that receives a string, pipes it through /usr/bin/tac, and
returns the output? Apparently the "def findLeanSysroot?" in
Lake/Config/InstallPath.lean is a good starting point, and I would
need to use IO.Process.Stdio.piped somewhere - but I am a newbie and
I'm struggling with the details...

Note: I mentioned tac above just to discuss a minimal example, but my
real objective is to use this thing here - luatree.lua - to draw 2D
trees in ASCII art... here's a screenshot:

https://github.com/leanprover/lean4/blob/master/src/lake/Lake/Config/InstallPath.lean#L121
http://anggtwu.net/eev-maxima.html#luatree



#####
#
# Lake.Load
# 2024jun21
#
#####

# «Lake.Load»  (to ".Lake.Load")
# (find-lean4prefile "lake/Lake/Load/Main.lean" "no previous manifest, creating one from scratch")
# (find-lean4prefile "lake/Lake/Load/Main.lean" "Load a `Workspace` for a Lake package by elaborating")
# (find-lean4prefile "lake/lakefile.lean" "supportInterpreter := true")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lake
import Lake.Load
#check Lake.logWarning
#check Lake.loadWorkspaceRoot
#check Lake.loadDepsFromEnv

-- end



#####
#
# latin-cross
# 2024apr20
#
#####

# «latin-cross»  (to ".latin-cross")
# (find-lean-links "✝")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '✝' *")
# (find-lean4prefile "Init/Meta.lean" "s.contains '✝' || s == \"_inaccessible\"")



#####
#
# LawfulFunctor
# 2024jun01
#
#####

# «LawfulFunctor»  (to ".LawfulFunctor")
# (to "Functor")
# (find-lean-links "LawfulFunctor")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'LawfulFunctor' *")
# (find-lean4prefile "Init/Prelude.lean" "only the operations and not" "laws (see `LawfulFunctor`)")
# (find-lean4prefile "Init/Control/Lawful.lean" "class LawfulFunctor")
# (find-lean4docr "monads/laws.lean#life-without-laws")




#####
#
# leading-dot-notation
# 2024may23
#
#####

# «leading-dot-notation»  (to ".leading-dot-notation")
# (find-fplean4page 194 "Leading Dot Notation")
# (find-fplean4text 194 "Leading Dot Notation")
# (find-fplean4doc "monads/conveniences#leading-dot-notation")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive N where
  | z         : N
  | s (n : N) : N

set_option trace.Elab.command true in
def N.tostr : N → String
  | .z   => "z"
  | .s n => "s" ++ N.tostr n

#check  N.s N.z
#eval  (N.s N.z).tostr

-- end




#####
#
# leading_parser
# 2024mar27
#
#####

# «leading_parser»  (to ".leading_parser")
# (to "FirstTokens")
# (to "synth")
# (find-lean-links "leading_parser")
# (find-lean4grep    "grep --color=auto -nRH --null -e leading_parser *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'leading_parser' *")
# (find-lean4prefile "Lean/Elab/BuiltinNotation.lean" "invalid `leading_parser` macros")
# (find-lean4prefile "Lean/Elab/BuiltinNotation.lean" "@[builtin_term_elab «leading_parser»]")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "def «precedence\ » := leading_parser")
# (find-lean4prefile "Lean/Parser/Term.lean" "def «fun» := leading_parser:maxPrec")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Leading.20parser/near/431690866 yz, 2024apr06
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/leading_parser.3F/near/438403571 me, 2024may13
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'firsttokens' *")
# (find-lean4prefile "Lean/Parser/Types.lean" "inductive FirstTokens where")
# (find-lean4prefile "Lean/Parser/Types.lean" "def toStr : FirstTokens → String")
-- (ee-copy-rest-3 nil "-- end" "/tmp/a.lean")

import Lean.Parser.Term
import Lean.Parser.Command
#print Lean.Parser.Command.visibility
namespace Lean
namespace Parser
def foo := leading_parser "foo "
#check foo
#check foo.info
#check foo.info.firstTokens
#eval  foo.info.firstTokens

#print foo
/-
def Lean.Parser.foo : Parser :=
withCache `Lean.Parser.foo
  (withAntiquot (mkAntiquot "foo" `Lean.Parser.foo true) (leadingNode `Lean.Parser.foo 1024 (symbol "bar ")))
-/

-- end

Kyle Miller: Usually it's

  ">> becomes space and f x y z becomes f(x, y, z)"

though sometimes the parser name for syntax can be a little different.

There are also transformations like many p becomes p* and many1 p
becomes p+, among some others.




#####
#
# Lean.Parser.Category
# 2024jun12
#
#####

# «Lean.Parser.Category»  (to ".Lean.Parser.Category")
# (to "declare_syntax_cat")
# (find-lean4pregrep "grep --color=auto -nRH --null -e ': Category := {}' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'declare_syntax_cat' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'antiquotation' *")






#####
#
# Mário Carneiro: The Type Theory of Lean
# 2024may07
#
#####

# «lean-type-theory»  (to ".lean-type-theory")
# (find-angg ".emacs.papers" "leanttmain")
# (find-angg ".emacs.papers" "leanttslides")
# https://github.com/digama0/lean-type-theory
# https://github.com/digama0/lean-type-theory/releases/download/v1.0/main.pdf
# https://github.com/digama0/lean-type-theory/releases/download/v1.0/slides.pdf
# https://github.com/digama0/lean-type-theory/archive/refs/tags/v1.0.tar.gz
# https://www.youtube.com/watch?v=3sKrSNhSxik
# (find-youtubedl-links "/sda5/videos/" nil "3sKrSNhSxik" nil "{stem}")
# (find-youtubedl-links "/sda5/videos/" "The_Type_Theory_of_Lean" "3sKrSNhSxik" ".mkv" "leantt")
# (code-video "leanttvideo" "/sda5/videos/The_Type_Theory_of_Lean-3sKrSNhSxik.mkv")
# (find-leanttvideo "0:00")

# (find-git-links "https://github.com/digama0/lean-type-theory" "leantt")
# (code-c-d "leantt" "~/usrc/lean-type-theory/")
# (find-leanttfile "")

(code-pdf-page  "leanttmain" "$S/https/github.com/digama0/lean-type-theory/releases/download/v1.0/main.pdf")
(code-pdf-text8 "leanttmain" "$S/https/github.com/digama0/lean-type-theory/releases/download/v1.0/main.pdf")
;; (find-leanttmainpage)
;; (find-leanttmaintext)
;; (find-leanttmainpage 8 "2.5   Definitions")
;; (find-leanttmaintext 8 "2.5   Definitions")
;; (find-leanttmainpage 9 "telescope")
;; (find-leanttmaintext 9 "telescope")

(code-pdf-page  "leanttslides" "$S/https/github.com/digama0/lean-type-theory/releases/download/v1.0/slides.pdf")
(code-pdf-text8 "leanttslides" "$S/https/github.com/digama0/lean-type-theory/releases/download/v1.0/slides.pdf")
;; (find-leanttslidespage)
;; (find-leanttslidestext)

https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Lean.20in.20the.20wild/near/296059360






#####
#
# let
# 2024mar09
#
#####

# «let»  (to ".let")
# (to "indentation")
# (find-fplean4page 50 "let unzipped")
# (find-fplean4text 50 "let unzipped")
# (find-fplean4page 50 "let rec")
# (find-fplean4text 50 "let rec")
# (find-fplean4page 67 "definition using :=")
# (find-fplean4text 67 "definition using :=")
# (find-fplean4page 67 "let bindings in do use a left arrow")
# (find-fplean4text 67 "let bindings in do use a left arrow")
# (find-leanmetadoc  "main/03_expressions#expressions")
# (find-leanmetadocr "main/03_expressions" "letE n t v b")
# (find-fplean4doc "getting-to-know/conveniences#local-definitions")
# (find-fplean4page 49 "Local Definitions")
# (find-fplean4text 49 "Local Definitions")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def abc : List Nat :=
  let a : Nat := 2
  let b : Nat := 10*a
  let c : Nat := 10*b
  [a,b,c]

#eval abc

def de : List Nat := let d : Nat := 3; let e : Nat := 10*d; [d,e]
#eval de

-- end




#####
#
# let_fun
# 2024jun02
#
#####

# «let_fun»  (to ".let_fun")
# (find-lean4prefile "Init/Prelude.lean" "@[irreducible] def letFun")
# (find-lean4pregrep "grep --color=auto -nRHw --null -e 'let' * | grep -aw fun")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def       sq1        (x : Nat) := x*x
def       sq2 := fun (x : Nat) => x*x
#eval let sq3 := fun (x : Nat) => x*x; sq3 5
#eval let sq4 := fun  x        => x*x; sq4 5

-- end




#####
#
# let mut
# 2024may30
#
#####

# «let-mut»  (to ".let-mut")
# (to "do-notation")
# (to "do-unchained")
# (find-fplean4doc "monad-transformers/do#mutable-variables")
# (find-fplean4doc "monad-transformers/do#what-counts-as-a-do-block")
# https://www.reddit.com/r/haskell/comments/z55hha/review_of_lean_4/
# https://lean-lang.org/papers/do.pdf
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def two1 : Nat := Id.run do
  let mut x := 0
  x := x + 1
  x := x + 1
  return x

def two2 : Nat :=
  let block : StateT Nat Id Nat := do
    modify (· + 1)
    modify (· + 1)
    return (← get)
  let (result, _finalState) := block 0
  result

-- end







#####
#
# letterlike
# 2024apr06
#
#####

# «letterlike»  (to ".letterlike")
# (find-lean-links "unicode")
# (find-lean-links "letterlike")
# (find-lean4doc)
# (find-lean4doc      "lexical_structure")
# (find-lean4docrfile "lexical_structure.md")
# (find-lean4docrfile "lexical_structure.md" "letterlike_symbols")
# (find-lean4docrfile "SUMMARY.md" "<!-- - [Lexical Structure](./lexical_structure.md) -->")
# (find-lean4prefile "Init/Meta.lean" "def isLetterLike (c : Char) : Bool :=")
# (find-lean-links "letterlike_symbols")
# (find-lean-links "letterlike")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'unicode' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'letterlike' *")




#####
#
# Linter
# 2024jun21
#
#####

# «Linter»  (to ".Linter")
# (find-lean4prefile "Init/Prelude.lean" "set_option linter.missingDocs true")
# (find-lean4prefile "Lean/Linter/UnusedVariables.lean")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

set_option linter.unusedVariables false

def foo3 [i1 : Monad m] [i2 : MonadState σ m]
         (a : Nat) : m Nat := do
  let xxxxxxxx := 42
  let b ← get
  return a

-- end




#####
#
# List
# 2024jun26
#
#####

# «List»  (to ".List")
# (find-fplean4page 36 "Linked Lists")
# (find-fplean4text 36 "Linked Lists")





#####
#
# logInfo
# 2024may18
#
#####

# «logInfo»  (to ".logInfo")
# (find-lean-links "logInfo")
# (find-es "lean" "metaprogramming")
# (find-leanmetadocrfile "")
# (find-leanmetadocrsh "find * | sort")
# (find-leanmetadocrgrep "grep --color=auto -nRH --null -e 'logInfo' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'logInfo' *")
# (find-leanmetadoc  "main/01_intro")
# (find-leanmetadoc  "main/01_intro#building-a-command")
# (find-leanmetadocr "main/01_intro" "### Building a command")
# (find-leanmetadocr "main/01_intro" "### Building a command" "`logInfo` to output \"success\"")
# (find-lean4prefile "Lean/Log.lean" "def logInfo")



#####
#
# Macro and macro
# 2024may26
#
#####

# «macro»  (to ".macro")
# (to "extractFrom")
# (to "exploring-data-2")
# (find-leanmetadoc  "main/01_intro#introducing-notation-defining-new-syntax")
# (find-leanmetadocr "main/01_intro" "### Introducing notation (defining new syntax)")
# (find-leanmetadoc  "main/06_macros")
# (find-leanmetadocr "main/06_macros" "@[macro lxor] def lxorImpl2 : Macro")
# (find-leanmetadoc  "main/06_macros#simplifying-macro-declaration")

# (find-lean4prefile "Init/Prelude.lean" "namespace Macro")
# (find-lean4prefile "Init/Prelude.lean" "abbrev Macro := Syntax → MacroM Syntax")
# (find-lean4prefile "lake/Lake/DSL/Script.lean" "@[macro scriptDecl]")

# (find-lean-links "macro")
# (find-leanmetadocrgrep "grep --color=auto -nRH --null -e 'macro' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'macro' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" macro \"' *")
# (find-lean4pregrep "grep --color=auto -nRHw --null -e 'Macro' *")
# (find-lean4pregrep "grep --color=auto -nRHw --null -e 'Macro' Init/Prelude.lean")
# (find-lean4pregrep "grep --color=auto -nRHw --null -e 'macro' *")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean

macro x:ident ":" t:term " ↦ " y:term : term => do
  `(fun $x : $t => $y)

#eval (x : Nat ↦ x + 2) 2 -- 4

macro x:ident " ↦ " y:term : term => do
  `(fun $x  => $y)

#eval (x ↦  x + 2) 2 -- 4

-- end



#####
#
# map
# 2024jun01
#
#####

# «map»  (to ".map")
# (find-lean4prefile "Init/Prelude.lean")
# (find-lean4prefile "Init/Prelude.lean" "class Monad")
# (find-lean4prefile "Init/Prelude.lean" "class Monad" "map      f x :=")
# (find-lean4prefile "Init/Prelude.lean" "class Applicative")
# (find-lean4prefile "Init/Prelude.lean" "class Applicative" "map      :=")
# (find-lean4prefile "Init/Prelude.lean" "class Functor")
# (find-lean4prefile "Init/Prelude.lean" "class Functor" "map :")




#####
#
# mapAddOneNil
# 2024may28
#
#####

# «mapAddOneNil»  (to ".mapAddOneNil")
# (to "elab-term")
# (find-leanmetapage 20 "def mapAddOneNil : Expr :=")
# (find-leanmetatext 20 "def mapAddOneNil : Expr :=")
# (find-leanmetadoc  "main/03_expressions#constructing-expressions")
# (find-leanmetadocr "main/03_expressions" "## Constructing Expressions")
# (find-leanmetadocr "main/03_expressions" "mapAddOneNil")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean
open Nat

def nat : Expr := .const ``Nat []

def addOne : Expr :=
  .lam `x nat
    (mkAppN (.const ``Nat.add []) #[.bvar 0, mkNatLit 1])
    BinderInfo.default

def mapAddOneNil : Expr :=
  mkAppN (.const ``List.map [levelOne, levelOne])
    #[nat, nat, addOne, .app (.const ``List.nil [levelOne]) nat]

#check           mapAddOneNil
#check do return mapAddOneNil

elab "mapAddOneNil" : term => return mapAddOneNil

#check  mapAddOneNil
set_option pp.universes true in
set_option pp.explicit true in
#check  mapAddOneNil
#reduce mapAddOneNil

-- end





#####
#
# match
# 2024mar10
#
#####

# «match»  (to ".match")
# (to "antiquotation")
# (find-angg ".emacs.papers" "fplean4" "28" "Pattern Matching")
# (find-angg ".emacs.papers" "fplean4" "57" "if let")
# (find-leanmetapage 16 "what about match statements")
# (find-leanmetatext 16 "what about match statements")
# (find-fplean4page 28 "Pattern Matching")
# (find-fplean4text 28 "Pattern Matching")
# (find-fplean4page 57 "if let")
# (find-fplean4text 57 "if let")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'match \"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'match' * | grep -a with")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'match' * | grep -a with | grep -a pat")
# (find-lean4prefile "Lean/Elab/Match.lean" "-- leading_parser \"match \" >>")
# (find-lean4prefile "Lean/Elab/Match.lean" "we don't know the type of `p` yet")
# (find-lean4prefile "Init/Notation.lean" "`(match $d:term with | $pat => $t | _ => $e)")

#eval match 2 with | 0 => true | (n + 1) => false
#eval match 2 with | 0 => true | (_ + 1) => false
#eval match 2 with
        | 0       => true
        | (_ + 1) => false




#####
#
# Abbreviation for match/with: "a sequence of `| pat => expr`"
# 2024may19
#
#####

# «match-bar»  (to ".match-bar")
# (to "Expr")
# (to "Expr" "| forallE .. =>")
# (find-lean4prefile "Lean/Parser/Command.lean" "")
# (find-lean4prefile "Lean/Parser/Command.lean" "a sequence of `| pat => expr`")
# (find-tpil4doc "induction_and_recursion#pattern-matching")
# (find-leanmetadoc  "main/05_syntax#matching-on-syntax")
# (find-leanmetadocr "main/05_syntax" "### Matching on `Syntax`")
# (find-leanmetadocr "main/05_syntax" "def isAdd11 : Syntax → Bool")
# (find-leanmetadoc  "main/03_expressions#constructing-expressions")
# (find-leanmetadocr "main/03_expressions" "## Constructing Expressions")
# (find-leanmetadocr "main/03_expressions" "| n, m =>")
# (find-fplean4doc "monads/conveniences#or-patterns")
# (find-fline "~/TH/eev-lean4.blogme" "match-bar")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean

def isAdd11 : Syntax → Bool
  | `(Nat.add 1 1) => true
  | _ => false

#eval isAdd11 (Syntax.mkApp (mkIdent `Nat.add) #[Syntax.mkNumLit "1", Syntax.mkNumLit "1"]) -- true
#eval isAdd11 (Syntax.mkApp (mkIdent `Nat.add) #[mkIdent `foo, Syntax.mkNumLit "1"]) -- false

-- end
-- (ee-copy-rest-3 nil "-- end" "/tmp/L/a.lean")

inductive N where
  | z         : N
  | s (n : N) : N

def foo1 : N → Bool
  | N.z   => true
  | N.s _ => false

def foo2 : N → Bool := (match · with
  | N.z   => true
  | N.s _ => false)

def foo3 (n : N) : Bool := match n with
  | N.z   => true
  | N.s _ => false

  def bar1    : N  → Bool                  | .z => true | .s _ => false
  def bar2    : N  → Bool := (match · with | .z => true | .s _ => false)
--def bar3    : N  → Bool :=  match · with | .z => true | .s _ => false  -- err
  def bar4 (n : N) : Bool :=  match n with | .z => true | .s _ => false

-- end




#####
#
# mdbook
# 2024may22
#
#####

# «mdbook»  (to ".mdbook")
# (to "alectryon")
# (find-es "nix")
# https://lean-lang.org/lean4/doc/dev/mdbook.html
# (find-lean4doc  "dev/mdbook")
# (find-lean4doc  "dev/mdbook#using-nix")
# (find-lean4docr "dev/mdbook" "### Using Nix")




#####
#
# mdgen
# 2024may22
#
#####

# «mdgen»  (to ".mdgen")
# (to "metaprogramming")
# https://github.com/Seasawher/mdgen
# (find-git-links "https://github.com/Seasawher/mdgen" "mdgen")
# (code-c-d "mdgen" "~/usrc/mdgen/")
# (find-mdgenfile "")
# (find-mdgenfile "README.md")
# (find-mdgenfile "Mdgen/")
# (find-mdgenfile "Mdgen/ConvertToMd.lean")
# (find-mdgenfile "Test/Src/First.lean")
# (find-mdgenfile "lakefile.lean")
# (find-mdgenfile "lakefile.lean" "/-- run test by `lake test` -/")
# (find-mdgengrep "grep --color=auto -niRH --null -e html *")
# (find-mdgengrep "grep --color=auto -niRH --null -e minted *")
# (find-mdgengrep "grep --color=auto -niRH --null -e pygments *")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv ~/usrc/mdgen/
cd      ~/usrc/
git clone https://github.com/Seasawher/mdgen
cd      ~/usrc/mdgen/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd      ~/usrc/mdgen/
git clean -dfx
touch .timestamp
sleep 1

lake test   |& tee olt

# (find-mdgensh "find . -newer .timestamp | sort")
# (find-mdgenfile "Test/Out/")
# (find-mdgenfile "Test/Out/First.md")
# (find-mdgenfile "Test/Out/Second/")
# (find-mdgenfile "Test/Out/Second/Second.md")



#####
#
# meta if
# 2024jun21
#
#####

# «meta-if»  (to ".meta-if")
# (find-lean4prefile "lake/Lake/DSL/Meta.lean" "meta if <c:term> then <a:command> else <b:command>")
# (find-lean-links "meta if")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'meta if' *")




#####
#
# minted
# 2024apr28
#
#####

# «minted»  (to ".minted")
# https://lean-lang.org/lean4/doc/syntax_highlight_in_latex.html
# (find-lean4doc "syntax_highlight_in_latex")
# (find-esgrep "grep --color=auto -nH --null -e minted *.e")




#####
#
# mkSyntaxQuotation
# 2024jun02
#
#####

# «mkSyntaxQuotation»  (to ".mkSyntaxQuotation")
# (to "info-scp-mainModule")
# (to "TSyntax")
# (to "checksyntax-test")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'mkSyntaxQuotation' *")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'MonadQuotation' *")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'MonadQuotation' * | grep -a instance")
# (find-lean4prefile "Lean/Elab/Quotation.lean" "def mkSyntaxQuotation")
# (find-leanmetadoc  "main/06_macros")
# (find-leanmetadocr "main/06_macros")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean.Elab.Command
open   Lean.Elab.Term.Quotation
#check mkSyntaxQuotation

elab "#check_syntax " t:term : command => do Lean.logInfo m!"{t}"
elab "#check_syntax " t:term : command => do Lean.logInfo m!"{repr t.raw}"
elab "#check_syntax " t:term : command => do Lean.logInfo (repr t.raw)
#check_syntax 42 + "foo"

#check    `(42 + "foo")
#check   (`(42 + "foo") : Lean.MacroM                  (Lean.TSyntax `term))
#check   (`(42 + "foo") : Lean.PrettyPrinter.UnexpandM (Lean.TSyntax `term))
def a := (`(42 + "foo") : Lean.MacroM                  (Lean.TSyntax `term))
def b := (`(42 + "foo") : Lean.PrettyPrinter.UnexpandM (Lean.TSyntax `term))

#check `(#h $x:str)
#check `(#help $x)

-- end

do
  let info ← Lean.MonadRef.mkInfoFromRefPos
  let scp ← Lean.getCurrMacroScope
  let mainModule ← Lean.getMainModule
  pure
      {
        raw :=
          Lean.Syntax.node3 info `term_+_ (Lean.Syntax.node1 info `num (Lean.Syntax.atom info "42"))
            (Lean.Syntax.atom info "+")
            (Lean.Syntax.node1 info `str (Lean.Syntax.atom info "\"foo\"")) }
              : ?m.1206 (Lean.TSyntax `term) (lsp)






#####
#
# Monad
# 2024mar24
#
#####

# «Monad»  (to ".Monad")
# (to "do-notation")
# (to "extends")
# (find-lean4prefile "Init/Prelude.lean" "class Bind")
# (find-lean4prefile "Init/Prelude.lean" "class Pure")
# (find-lean4prefile "Init/Prelude.lean" "class Functor")
# (find-lean4prefile "Init/Prelude.lean" "class Applicative")
# (find-lean4prefile "Init/Prelude.lean" "class Monad")
# (find-lean4prefile "Init/Prelude.lean" "class Monad" "extends Applicative")

# (find-lean4doc "monads/intro")
# (find-lean4doc "monads/functors.lean")
# (find-lean4doc "monads/applicatives.lean")
# (find-lean4doc "monads/monads.lean")
# (find-lean4doc "monads/readers.lean")
# (find-lean4doc "monads/states.lean")
# (find-lean4doc "monads/except.lean")
# (find-lean4doc "monads/transformers.lean")
# (find-lean4doc "monads/laws.lean")

# (find-fplean4page 71 "def twice (action : IO Unit) : IO Unit")
# (find-fplean4text 71 "def twice (action : IO Unit) : IO Unit")
# (find-fplean4page 79 "Worked Example: cat")
# (find-fplean4text 79 "Worked Example: cat")
# (find-fplean4page 164 "The Monad Type Class")
# (find-fplean4text 164 "The Monad Type Class")
# (find-fplean4page 165 "General Monad Operations")
# (find-fplean4text 165 "General Monad Operations")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check Monad

-- end




#####
#
# Monad-map
# 2024jun12
#
#####

# «Monad-map»  (to ".Monad-map")
# (find-fplean4doc "monad-transformers/transformers#lifting")
# https://github.com/leanprover-community/mathlib4/wiki/Monad-map

A solid arrow upwards from A to B means "when in the A Monad, anything
in B can be called directly", i.e. there is a lift from B to A. (If
this arrow is labeled, you must call that function to do so.)

A dotted line downwards from B to A means that you can call a function
(possibly with some extra arguments, such as initial state) to run B
inside A. Note that many of these functions have apostrophe variants
(e.g. TermElabM.run and TermElabM.run'): run typically returns the
final state of the monad that we're running inside the other monad
along with the actual return value, whereas run' simply discards it.

This diagram is ordered from bottom to top, with simpler monads at the
bottom and more complex ones at the top. As such, lifts go up, and
run-like functions go down.

# (find-fline "~/tmp/monad-map.png")
# (xz         "~/tmp/monad-map.png")

Note that IO and EIO are taken to each other by the functions IO.toEIO
and EIO.toIO, neither of which is a lift, so in this case, the
top-to-bottom directionality of dotted lines isn't meaningful.

Many application-specific monads are defined in terms of monad
transformers on top of typical metaprogramming monads; for example, in
addition to SimpM, we have SimpAll.M, and many others. Instead of
having dedicated functions to run in the monad they're defined on top
of, many of these simply use the function given by the monad
transformer, e.g. StateRefT'.run for SimpM to return to the MetaM
monad. SimpM is given here as an example.

Note that runTermElabM and liftTermElabM both turn a TermElabM into a
CommmandElabM (and neither is a MonadLift). The difference is that
runTermElabM allows the TermElabM computation to act on any scoped
free variables (introduced by the variable command), whereas
liftTermElabM doesn't. As a mnemonic: the run lets us specify some
part of the "initial state" for the monad computation (like e.g.
StateT.run), whereas the lift (as usual) doesn't.

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean

#check Lean.Elab.Tactic.TacticM
#check Lean.Elab.Term.TermElabM
#check Lean.Meta.MetaM
#check Lean.CoreM
#check EIO
#check IO
#check Lean.Server.RequestM
#check Lean.PrettyPrinter.Delaborator.DelabM
#check BaseIO
#check Lean.Elab.Command.CommandElabM
#check Lean.Meta.Simp.SimpM
#check Lean.Elab.Frontend.FrontendM
-- end




#####
#
# Monad S
# 2024jun22
#
#####

# «Monad-S»  (to ".Monad-S")
# (to "Id.run")
# (to "outParam")
# (find-lean-links "MonadState")
# (find-lean-links "must be an inductive type")
# (find-lean4pregrep "grep --color=auto -nRH  --null -e 'MonadState' *")
# (find-lean4pregrep "grep --color=auto -nRHw --null -e 'MonadState' *")
# (find-lean4pregrep "grep --color=auto -nRH  --null -e 'Monad' * | grep instance")
# (find-lean4pregrep "grep --color=auto -nRH  --null -e 'Pure' * | grep instance")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

universe u
universe v

def S (α : Type) : Type := String × α

instance : Monad S where
  pure o    := ⟨"", o⟩
  bind sa f := ⟨sa.fst, (f (sa.snd)).snd⟩
--bind sa f := f (sa.snd)

#check show S Nat from do return 42
#eval  show S Nat from do return 42
#eval  show IO Nat from do return 42

#check List.pure
#check List.bind
#check List.pure Nat
#check List.pure 42

-- end



# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

universe u
universe v

def S (α : Type u) : Type u := String × α   -- "S" stands for both "State" and "String"

instance : Monad S where
  pure o := ⟨"", o⟩
  bind {α : Type u} {β : Type u}
       (sa : S α) (f : α → S β) : S β :=    -- or just: bind sa f := ...
    let state := sa.fst
    let a     := sa.snd
    ⟨state, (f a).snd⟩

#check                   do return 42
#check show S Nat from   do return 42
#eval  show S Nat from   do return 42

-- end

# (find-lean-links "MonadStateOf")




# (find-lean4prefile "Init/Prelude.lean" "class MonadState ")
# (find-lean4prefile "Init/Prelude.lean" "class MonadStateOf ")




#####
#
# modules
# 2024may29
#
#####

# «modules»  (to ".modules")
# (to "import")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rv   /tmp/MA*
mkdir -p /tmp/MA/MB/MC/

# (ee-copy-rest-3 nil "-- end" "/tmp/MA.lean")
def a := 42
-- end

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")
import MA
#check a
-- end




#####
#
# mutual
# 2024jun05
#
#####

# «mutual»  (to ".mutual")
# (to "inductive")
# (to "partial-mutual")
# (find-fplean4doc  "dependent-types/universe-pattern")
# (find-fplean4docr "dependent-types/universe-pattern" "in a `mutual` block")
# (find-fline "~/usrc/fp-lean/examples/Examples/DependentTypes/Finite.lean" "-- ANCHOR: MutualStart")
# (find-fplean4file "examples/Examples/DependentTypes/Finite.lean" "-- ANCHOR: MutualStart")
# (find-lean4prefile "Lean/Declaration.lean" "The kernel compiles (mutual) inductive declarations")

# (find-lean-links "inductive")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'inductive' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'inductive fam' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'mutual inductive' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'mutually inductive' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'mutual' *")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

mutual
  inductive A where
    | a0         : A
    | a1 (b : B) : A

  inductive B where
    | b0         : B
    | b1 (a : A) : B
end

mutual
  def A.foo : A → String
    | A.a0   => "a0"
    | A.a1 b => "a1_" ++ (B.foo b)

  def B.foo : B → String
    | B.b0   => "b0"
    | B.b1 a => "b1_" ++ (A.foo a)
end

#check        B.b1 (A.a1 B.b0)
#check B.foo (B.b1 (A.a1 B.b0))
#eval  B.foo (B.b1 (A.a1 B.b0))

-- end







#####
#
# mySpecialCheck
# 2024may24
#
#####

# «mySpecialCheck»  (to ".mySpecialCheck")
# (to "TermElabM")
# (find-leanmetadoc  "main/07_elaboration")
# (find-leanmetadocr "main/07_elaboration")
# (find-leanmetadocr "main/07_elaboration" "mySpecialCheck")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean Elab Command Term Meta

elab "#check" "mycheck" : command => do logInfo "Got ya!"

@[command_elab Lean.Parser.Command.check] def mySpecialCheck : CommandElab := fun stx => do
  if let some str := stx[1].isStrLit? then
    logInfo s!"Specially elaborated string literal!: {str} : String"
  else
    throwUnsupportedSyntax

#check mycheck -- Got ya!
#check "Hello" -- Specially elaborated string literal!: Hello : String
#check Nat.add -- Nat.add : Nat → Nat → Nat

-- end



#####
#
# Name
# 2024jun20
#
#####

# «Name»  (to ".Name")
# (find-lean4prefile "Init/Prelude.lean" "inductive Name where")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Command.instance' *")
# (find-leanmetapage 110 "let name := mkIdent $ Name.mkSimple str")
# (find-leanmetatext 110 "let name := mkIdent $ Name.mkSimple str")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean
#check Name
#check Name.mkSimple
#check Name.mkNum
#check  ``Lean.Parser.Command.instance
#check       ``Parser.Command.instance
def name1 := ``Parser.Command.instance
def name2 := Name.mkNum name1 42
def name3 := Name.mkNum "foo" 42
#eval name1
#eval name2
#eval name3

def f1 : Name → String
  | .anonymous                       => ".anonymous"
  | .str (pre : Name) (str : String) => s!".str ({f1 pre}) ({str})"
  | .num (pre : Name) (i : Nat)      => s!".num ({f1 pre}) ({i})"

def f2 : Name → String
  | .anonymous                  => ".anonymous"
  | .str _ (str : String)       => str
  | .num (pre : Name) (i : Nat) => s!".num ({f2 pre}) ({i})"

#eval f1 name1
#eval f1 name2
#eval f1 name3
#eval f2 name1
#eval f2 name2
#eval f2 name3

-- end




#####
#
# namespace
# 2024mar15
#
#####

# «namespace»  (to ".namespace")
# «section»    (to ".section")
# (to "import")
# (to "open")
# (find-lean-links "namespace")
# (find-angg ".emacs.papers" "tpil4" "15" "2.7. Namespaces")
# (find-angg ".emacs.papers" "tpil4" "83" "6.3. More on Namespaces")
# (find-tpil4page  15 "2.7. Namespaces")
# (find-tpil4text  15      "Namespaces")
# (find-tpil4page  16      "The open command")
# (find-tpil4text  16      "The open command")
# (find-tpil4page  83 "6.3. More on Namespaces")
# (find-tpil4text  83      "More on Namespaces")
# (find-tpil4page 167 "open scoped <namespace>")
# (find-tpil4text 167 "open scoped <namespace>")
# (find-tpil4file "dependent_type_theory.md" "# Namespaces")
# (find-tpil4file "interacting_with_lean.md" "More on Namespaces")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "only `S` and `K` under `Combinator.Calculus`")

# (find-lean4doc "sections")
# (find-lean4doc "namespaces")
# (find-lean4doc "tour#functions-and-namespaces")
# (find-lean4docrfile "namespaces.md" "# Namespaces")
# (find-lean4docrfile "tour.md" "# Functions and Namespaces")

# (find-angg ".emacs.papers" "fplean4" "56" "Namespaces")
# (find-fplean4page 56 "Namespaces")
# (find-fplean4text 56 "Namespaces")

# (find-lean4pregrep "grep --color=auto -nRH --null -e '`namespace`' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '`open`' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '`section`' *")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "The `open` command")

# (find-tpil4file "type_classes.md" "open scoped <namespace>")
# (find-lean4prefile "Lean/Elab/BuiltinTerm.lean" "@[builtin_term_elab «open\ »]")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "@[builtin_command_elab «namespace»]")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "@[builtin_command_elab «section»]")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "@[builtin_command_elab «open\ »]")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def «namespace»")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def «section»")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"namespace \"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"section \"'   *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"open \"'      *")

# (find-lean4prefile "Lean/Parser/Extra.lean" "possibly with namespaces")
# (find-lean4prefile "Lean/Parser/Term.lean" "(appending the current namespaces)")
# (find-lean4prefile "Lean/ResolveName.lean" "namespace ResolveName")
# (find-lean4prefile "Lean/Server/Completion.lean" "Search namespaces")
# (find-lean4prefile "Lean/Environment.lean" "Environment extension for tracking all `namespace`")

# (find-lean-links "registerNamespace")
# (find-lean-links "namespace")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'registerNamespace' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'builtin_command_elab' *")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "@[builtin_command_elab «namespace»]")


# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

namespace A
  namespace B
    def c := 42
  end B
end A

#check A.B.c

namespace A
  #check A.B.c
  #check   B.c
end A

namespace A.B
  #check A.B.c
  #check   B.c
  #check     c
end A.B

namespace A
  namespace B
    #check A.B.c
    #check   B.c
    #check     c
  end B
end A

--#check c
open A.B
#check c

-- end

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

namespace A
  def c := "Ac"
end A
namespace B
  def c := "Bc"
end B

#eval A.c
#eval B.c
open A
#eval c
open B
#eval c  -- err: ambiguous

-- end






#####
#
# notation
# 2024mar28
#
#####

# «notation»  (to ".notation")
# (find-lean-links "notation")
# (find-tpil4grep "grep --color=auto -nH --null -e 'notation' *.md")
# (find-tpil4file "interacting_with_lean.md" "notation ``≤`` to the `isPrefix` relation")
# (find-tpil4file "interacting_with_lean.md" "notation:65 lhs:65 \" + \" rhs:66")
# (find-tpil4file "tactics.md" "The notation ``←t``")
# (find-tpil4file "type_classes.md" "how the notation `a*b` is defined in Lean")
# (find-lean4docgrep "grep --color=auto -nRH --null -e 'notation' *")
# (find-leanmetadocrgrep "grep --color=auto -nRH --null -e 'notation' *")
# (find-lean4prefile "Init/Notation.lean" "\" ∧ \"")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "@[builtin_command_parser] def «notation\ »")
# (find-leanmetadoc  "main/03_expressions#constructing-expressions" "double backticks")
# (find-leanmetadoc  "main/05_syntax")
# (find-leanmetadoc  "main/05_syntax#free-form-syntax-declarations")
# (find-leanmetadoc  "main/05_syntax#free-form-syntax-declarations" "scoped syntax")
# (find-leanmetadocr "main/05_syntax" "### Free form syntax declarations")
# (find-leanmetadocr "main/05_syntax" "`command`, this is the category for top-level commands")
# (find-leanmetadoc  "main/05_syntax#declaration-helpers")
# (find-leanmetadocr "main/05_syntax" "### Declaration helpers")
# (find-leanmetadocr "main/05_syntax" "notation:65 lhs:65 \" ~ \" rhs:65 => (lhs - rhs)")



#####
#
# opaque
# 2024jun03
#
#####

# «opaque»  (to ".opaque")
# (to "partial")



#####
#
# open
# 2024jun14
#
#####

# «open»  (to ".open")
# (to "namespace")
# (find-tpil4page  16 "The open command")
# (find-tpil4text  16 "The open command")
# (find-tpil4page 167 "open scoped <namespace>")
# (find-tpil4text 167 "open scoped <namespace>")




#####
#
# Options
# 2024jun02
#
#####

# «Options»  (to ".Options")
# (to "instance-implicits")
# (to "pp.universes")
# (to "trace.Elab.command")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'pp.notation' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'pp.universes' *")
# (find-lean4prefile "Lean/PrettyPrinter/Delaborator/Options.lean" "pp.notation : Bool := {")
# (find-lean4prefile "Lean/PrettyPrinter/Delaborator/Options.lean" "pp.universes : Bool := {")
# (find-lean4prefile "Lean/PrettyPrinter/Delaborator/Options.lean" "pp.explicit : Bool := {")
# (find-lean4prefile "Lean/PrettyPrinter/Delaborator/Options.lean" "pp.instances")
# (find-lean4doc  "monads/monads.lean#basic-monad-example")
# (find-lean4docr "monads/monads.lean#basic-monad-example")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

-- end





#####
#
# <|>, a.k.a. orelse
# 2024may15
#
#####

# «orelse»  (to ".orelse")
# (find-lean4prefile "Init/Notation.lean" "`p1 <|> p2` is shorthand for `orelse(p1, p2)`")
# (find-lean4prefile "Init/Notation.lean" "`(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂))")



#####
#
# outParam
# 2024jun22
#
#####

# «outParam»  (to ".outParam")
# (find-lean4pregrep "grep --color=auto -niRH  --null -e 'outparam' *")
# (find-lean4pregrep "grep --color=auto -niRHw --null -e 'outparam' *")
# (find-lean4prefile "Init/Prelude.lean" "class Membership (α : outParam (Type u)) (γ : Type v)")
# (find-fplean4page 117 "declared with the outParam modifier:")
# (find-fplean4text 117 "declared with the outParam modifier:")
# (find-fplean4page 123 "class GetElem (coll : Type) (idx : Type) (item : outParam Type)")
# (find-fplean4text 123 "class GetElem (coll : Type) (idx : Type) (item : outParam Type)")
# (find-fplean4page 148 "(indicated by an outParam modifier)")
# (find-fplean4text 148 "(indicated by an outParam modifier)")
# (find-fplean4page 251 "class MonadReader (ρ : outParam (Type u))")
# (find-fplean4text 251 "class MonadReader (ρ : outParam (Type u))")
# (find-fplean4page 252 "Just as in MonadReader , the environment ρ is an outParam .")
# (find-fplean4text 252 "Just as in MonadReader , the environment ρ is an outParam .")

# (find-lean4pregrep "grep --color=auto -niRHw --null -e 'optparam' *")





#####
#
# p123456
# 2024jun09
#
#####

# «p123456»  (to ".p123456")
# (to "inductive-Arith")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive A where
  | n     (n : Nat) : A
  | minus (b c : A) : A
  | pow   (b c : A) : A
  deriving Repr

def paren : A → String
  | .n n       => toString n
  | .minus b c => "(" ++ paren b ++ "-" ++ paren c ++ ")"
  | .pow   b c => "(" ++ paren b ++ "^" ++ paren c ++ ")"

def p123    : A := A.minus (A.minus (A.n 1) (A.n 2)) (A.n 3)
def p456    : A := A.pow (A.n 4) (A.pow (A.n 5) (A.n 6))
def p123456 : A := A.minus p123 p456

#eval paren p123456   --> "(((1-2)-3)-(4^(5^6)))"

declare_syntax_cat catA

syntax num                      : catA
syntax:50 catA:50 " - " catA:51 : catA
syntax:70 catA:71 " ^ " catA:70 : catA
syntax "[: " catA " :]"         : term

macro_rules | `([: $n:num :]) => `(A.n ($n))
macro_rules | `([: $b:catA - $c:catA :]) => `(A.minus ([: $b :]) ([: $c :]))
macro_rules | `([: $b:catA ^ $c:catA :]) => `(A.pow   ([: $b :]) ([: $c :]))

#check      [: 1 - 2 - 3 - 4 ^ 5 ^ 6 :]
#eval paren [: 1 - 2 - 3 - 4 ^ 5 ^ 6 :]   --> "(((1-2)-3)-(4^(5^6)))"

-- end




#####
#
# Partax
# 2024jun14
#
#####

# «Partax»  (to ".Partax")
# https://github.com/tydeu/lean4-partax
# (find-git-links "https://github.com/tydeu/lean4-partax" "partax")
# (code-c-d "partax" "~/usrc/lean4-partax/")
# (find-partaxfile "")
# (find-partaxfile "README.md")
# (find-partaxfile "tests/lcompile.lean" "#match_stx term term | 2 + 2 = 4")
# (find-partaxfile "Partax/Test/Basic.lean" "@[scoped command_parser] def matchStx :=")
# (find-partaxfile "Partax/Test/Basic.lean" "@[macro matchStx] def expandMatchStx")
# https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Introducing.20Partax.2C.20the.20Parser.20Compiler/near/379967441

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv  ~/usrc/lean4-partax/
mkdir -p ~/usrc/
cd       ~/usrc/
git clone https://github.com/tydeu/lean4-partax
cd       ~/usrc/lean4-partax/

git clean -dfx
git reset --hard
time ./test.sh      2>&1 | tee ot     ;# takes a few minutes

# (find-file "~/usrc/lean4-partax/tests/lcompile.lean")


# (ee-copy-rest-3m nil "-- end" (ee-partaxfile "a.lean"))
import Lean
import Partax
open scoped Partax
open Lean Elab Command
compile_parser Lean.Parser.Term.attributes => attrs -- with CompileConfig.lParse
#eval attrs.run' "@[instance high, inline]" -- TSyntax `Lean.Parser.Term.attributes
-- end

# (ee-copy-rest-3m nil "-- end" (ee-partaxfile "a.lean"))

import Lean
import Partax

open scoped Partax

compile_parser Lean.Parser.Term.attributes => attrs -- with CompileConfig.lParse
#eval attrs.run' "@[instance high, inline]" -- TSyntax `Lean.Parser.Term.attributes

compile_parser_category prio -- with CompileConfig.lParse
#eval prio.run' "default + default" -- TSyntax `prio

open Lean Elab Command in -- 2000
#eval liftMacroM (m := CommandElabM) do
  match prio.run' "default + default" with
  | .ok stx => evalPrio stx
  | .error e => Macro.throwError e

-- end



#####
#
# #match_stx2
# 2024jun16
#
#####

# «Partax-match_stx2»  (to ".Partax-match_stx2")
# (code-c-d "partax" "~/usrc/lean4-partax/")
# (find-partaxfile "")
# (find-partaxfile "README.md")
# (find-partaxfile "tests/lcompile.lean" "#match_stx term term | 2 + 2 = 4")
# (find-partaxfile "Partax/Test/Basic.lean" "@[scoped command_parser] def matchStx :=")
# (find-partaxfile "Partax/Test/Basic.lean" "@[macro matchStx] def expandMatchStx")
# (ee-copy-rest-3m nil "-- end" (ee-partaxfile "a.lean"))

import Partax.Test.Basic
open   Partax.Test
#check expandMatchStx

open Lean
open Parser
namespace MyTests

@[scoped command_parser] def matchStx2 := leading_parser
  "#match_stx2 " >> ident >> termParser >> " | " >> parserOfStack 2

@[macro matchStx2] def expandMatchStx : Macro := fun matchStx => do
  let stx := matchStx[4]
  let some src := stx.updateTrailing "".toSubstring |>.reprint
    | Macro.throwError "cannot reprint syntax"
  let p : Ident := ⟨matchStx[2]⟩
  let test ← `((matchStxFn · $(quoteSyntax stx)))
  `(#eval $(p).run' $(quote src) >>= $test)

#match_stx2 term term | 2 + 2 = 4
-- def_from_match_stx a224 := term term | 2 + 2 = 4
-- #eval a224

end MyTests

-- end




#####
#
# #parse_term
# 2024jun15
#
#####

# «parse_term»  (to ".parse_term")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/.E2.9C.94.20How.20to.20test.20a.20syntax
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

elab "#parse_term " _t:term : command => pure ()
#parse_term 2 + 2

-- end






#####
#
# partial
# 2024mar23
#
#####

# «partial»  (to ".partial")
# (to "Inhabited")
# (to "termination")
# (to "opaque")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'partial' *")
# (find-fplean4page 80 "The dump function is declared partial")
# (find-fplean4text 80 "The dump function is declared partial")
# (find-fplean4doc "hello-world/cat#streams")
# (find-leanmetadoc  "main/02_overview#type-correctness")
# (find-leanmetadocr "main/02_overview" "### Type correctness" "use the `partial` keyword")
# (find-lean4prefile "Lean/Declaration.lean" "inductive DefinitionSafety where")
# (find-lean4prefile "Lean/Declaration.lean" "inductive Declaration where")
# (find-lean4prefile "Lean/Declaration.lean" "| opaqueDecl")
# (find-lean4prefile "Lean/Declaration.lean" "| mutualDefnDecl")
# (find-lean4prefile "Lean/Elab/MutualDef.lean")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def bufsize : USize := 20 * 1024

partial def dump (stream : IO.FS.Stream) : IO Unit := do
  let buf ← stream.read bufsize
  if buf.isEmpty then
    pure ()
  else
    let stdout ← IO.getStdout
    stdout.write buf
    dump stream

#print dump  -- opaque

-- end




#####
#
# partial-mutual - "This trick is useful if you need mutual recursion among your instances"
# 2024jun04
#
#####

# «partial-mutual»  (to ".partial-mutual")
# (to "mutual")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/.22failed.20to.20synthesize.20instance.20ToLuaTree.20Name.22.20inside.20.22insta/near/441936047

partial def toLuaTreeName (name : Name) : String :=
  let _ : ToLuaTree Name := ⟨toLuaTreeName⟩
  match name with
  | .anonymous   => "(.anon)"
  | .str pre str => zconcat ".str" [toLuaTree pre, q str]
  | .num pre i   => "(.n)"

instance : ToLuaTree Name := ⟨toLuaTreeName⟩

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")


-- end






#####
#
# polymorphism
# 2024may19
#
#####

# «polymorphism»  (to ".polymorphism")
# (find-angg ".emacs.papers" "fplean4")
# (find-fplean4page 34 "Polymorphism")
# (find-fplean4text 34 "Polymorphism")



#####
#
# posOrNegThree
# 2024may23
#
#####

# «posOrNegThree»  (to ".posOrNegThree")
# (find-fplean4page 36 "def posOrNegThree")
# (find-fplean4text 36 "def posOrNegThree")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

inductive Sign where
  | pos
  | neg

def posOrNegThree (s : Sign) : match s with
  | Sign.pos => Nat
  | Sign.neg => Int := match s with
    | Sign.pos => (3 : Nat)
    | Sign.neg => (-3 : Int)

#eval posOrNegThree Sign.pos
#eval posOrNegThree Sign.neg

-- end



#####
#
# postulate
# 2024may20
#
#####

# «postulate»  (to ".postulate")
# (to "axiom")
# (find-THfile "eev-lean4.blogme" "question-postulate")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/How.20do.20I.20translate.20Agda's.20.22postulate.22.20to.20Lean.3F/near/439561780
# (find-es "agda" "postulates")



#####
#
# pp.notation
# 2024jun02
#
#####

# «pp.notation»  (to ".pp.notation")
# (to "Options")
# (to "sleep1")




#####
#
# pp.universes
# 2024may28
#
#####

# «pp.universes»  (to ".pp.universes")
# (to "Options")
# (find-leanmetapage 18 "set_option pp.universes true in")
# (find-leanmetatext 18 "set_option pp.universes true in")
# (find-leanmetadocr "main/03_expressions" "set_option pp.universes true in")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check @List.map

set_option pp.universes true in
#check @List.map

-- end





#####
#
# Pratt parser
# 2024mar27
#
#####

# «pratt-parser»  (to ".pratt-parser")
# (to "ullrichmp")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'pratt' *")
# (find-lean4prefile "Lean/Parser/Basic.lean" "def prattParser")
# (find-lean4docrfile "metaprogramming-arith.md" "(a:60 + b:61):60 + c")




#####
#
# precedence
# 2024jun12
#
#####

# «precedence»  (to ".precedence")
# (to "binop")
# (find-leanmetapage 5 "the" "higher the number, the tighter the binding")
# (find-leanmetatext 5 "the" "higher the number, the tighter the binding")
# (find-lean4prefile "Init/Notation.lean" "@[inherit_doc] infixl:65 \" + \"   => HAdd.hAdd")
# (find-lean4prefile "Init/Notation.lean" "macro_rules | `($x + $y)   => `(binop% HAdd.hAdd $x $y)")




#####
#
# #print
# 2024mar11
#
#####

# «print»  (to ".print")
# (find-fplean4page 190 "#print Nat")
# (find-fplean4text 190 "#print Nat")
# (find-fplean4page 191 "#print IO.Error")
# (find-fplean4text 191 "#print IO.Error")
# (find-tpil4grep "grep --color=auto -nH --null -e '#print' *.md")
# (find-tpinleanpage (+ 6 89) "6.8 Displaying Information")
# (find-tpinleantext (+ 6 89) "6.8 Displaying Information")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def print")
# (find-lean4prefile "Lean/Elab/Print.lean" "@[builtin_command_elab «print\ »] def elabPrint :")
# (find-lean4prefile "Lean/Elab/Print.lean" "private def printIdCore (id : Name) :")
# (find-lean-links "print")
# (find-lean-links "#print")
# (find-lean-links "printAxioms")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'print' * | grep -a command")

# (to "leading_parser")
Repr doesn't have anything to do with #print. What #print does is
pretty print a declaration, whose value is an Expr.

-- Old:
#print definition                      :   display   definition
#print inductive                       :   display   an inductive type and its constructors
#print notation                        :   display   all notation
#print notation <tokens>               :   display   notation using any of the tokens
#print axioms                          :   display   assumed axioms
#print options                         :   display   options set by user
#print prefix <namespace>              :   display   all declarations in the namespace
#print classes                         :   display   all classes
#print instances <class name>          :   display   all instances of the given class
#print fields <structure>              :   display   all fields of a structure



#####
#
# #print inductive
# 2024jun20
#
#####

# «print-inductive»  (to ".print-inductive")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '#print' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'Command.print' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'number of parameters' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'printInduct' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" \\.\\. \"' *")
# (find-lean4prefile "Lean/Elab/Print.lean" "@[builtin_command_elab «print\ »]")
# (find-lean4prefile "Lean/Elab/Print.lean" "private def printInduct")
# (find-lean4prefile "Lean/Elab/Print.lean" "printInduct id us numParams t ctors u")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean
open   Nat
#print Nat
#print Expr
#print Expr.const
#check Expr.const

-- end

 a.lean    36   1 info            inductive Lean.Expr : Type
 number of parameters: 0
 constructors:
 Lean.Expr.bvar : Nat → Expr
 Lean.Expr.fvar : FVarId → Expr
 Lean.Expr.mvar : MVarId → Expr
 Lean.Expr.sort : Level → Expr
 Lean.Expr.const : Name → List Level → Expr
 Lean.Expr.app : Expr → Expr → Expr
 Lean.Expr.lam : Name → Expr → Expr → BinderInfo → Expr
 Lean.Expr.forallE : Name → Expr → Expr → BinderInfo → Expr
 Lean.Expr.letE : Name → Expr → Expr → Expr → Bool → Expr
 Lean.Expr.lit : Literal → Expr
 Lean.Expr.mdata : MData → Expr → Expr
 Lean.Expr.proj : Name → Nat → Expr → Expr (lsp)





#####
#
# Prod
# 2024jun13
#
#####

# «Prod»  (to ".Prod")
# (find-fplean4page 42 "Prod")
# (find-fplean4text 42 "Prod")
# (find-fplean4doc "getting-to-know/polymorphism#prod")
# (find-tpil4page 106 "structure Prod")
# (find-tpil4text 106 "structure Prod")
# (find-lean4prefile "Init/Prelude.lean" "structure Prod (α : Type u) (β : Type v) where")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")



-- end





#####
#
# project
# 2024may29
#
#####

# «project»  (to ".project")
# (to "lake-new-greeting")
# (find-fplean4doc "hello-world/starting-a-project")
# (find-leanrefdoc "using_lean#id3" "1.3.2. Multi-file Projects")




#####
#
# Pure
# 2024jun22
#
#####

# «Pure»  (to ".Pure")
# (find-lean4prefile "Init/Prelude.lean" "class Pure (f : Type u → Type v) where")




#####
#
# Range
# 2024may24
#
#####

# «Range»  (to ".Range")
# (find-lean4prefile "Init/Data/Range.lean" "[i:j]")
# (find-lean4prefile "Init/Data/Range.lean" "structure Range where")
# (find-lean4prefile "Init/Data/Range.lean" "  start : Nat := 0")
# (find-lean4prefile "Init/Core.lean" "inductive ForInStep ")
# (find-lean4prefile "Init/Core.lean" ""class ForIn ")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check [:(5:Nat)]
#check [:5]
#check [:(5:Int)] -- err

-- end





#####
#
# ReaderT
# 2024may21
#
#####

# «ReaderT»  (to ".ReaderT")
# (to "run_cmd")
# (find-lean4prefile "Lean/Elab/Command.lean" "abbrev CommandElabCoreM (ε) := ReaderT Context")
# (find-lean4prefile "Init/Prelude.lean" "def ReaderT")
# (find-fplean4page 250 "Adding a Reader to Any Monad")
# (find-fplean4text 250 "Adding a Reader to Any Monad")
# (find-fplean4page 254 "A Monad Construction Kit")
# (find-fplean4text 254 "A Monad Construction Kit")
# (find-fplean4doc "monads/arithmetic#custom-environments")
# (find-fplean4doc "monads/arithmetic#readers-with-failure")
# (find-fplean4doc "monads/arithmetic#readers-with-failure")




#####
#
# reduce
# 2024may28
#
#####

# «reduce»  (to ".reduce")
# (to "whnf")
# (find-leanmetadoc  "main/04_metam")
# (find-leanmetadoc  "main/04_metam#full-normalisation")
# (find-leanmetadocr "main/04_metam" "### Full Normalisation")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Lean.Expr Lean.Meta

def someNumber : Nat := (· + 2) $ 3
#eval Expr.const ``someNumber []
#eval reduce (Expr.const ``someNumber [])
#reduce someNumber

def traceConstWithTransparency (md : TransparencyMode) (c : Name) :
    MetaM Format := do
  ppExpr (← withTransparency md $ reduce (.const c []))

@[irreducible] def irreducibleDef : Nat      := 1
def                defaultDef     : Nat      := irreducibleDef + 1
abbrev             reducibleDef   : Nat      := defaultDef + 1

#eval traceConstWithTransparency .reducible ``reducibleDef

set_option pp.explicit true
#eval traceConstWithTransparency .reducible ``reducibleDef
#eval traceConstWithTransparency .instances ``reducibleDef
#eval traceConstWithTransparency .default ``reducibleDef
#eval traceConstWithTransparency .all ``reducibleDef

-- end



#####
#
# repl
# 2024jun09
#
#####

# «repl»  (to ".repl")
# https://github.com/leanprover-community/repl
# https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/How.20to.20interface.20with.20Lean.20from.20another.20language.3F
# https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/lean4_jupyter.3A.20A.20Lean.204.20Jupyter.20kernel.20via.20repl



#####
#
# Repr and ToString
# 2024mar24
#
#####

# «Repr»  (to ".Repr")
# (to "structure")
# (to "instance")
# (to "inductive-Nat")
# (to "synth")
# (find-fplean4page 19 "deriving Repr")
# (find-fplean4text 19 "deriving Repr")

# (find-lean-links "Repr")
# (find-lean4presh "find * | sort")
# (find-lean4presh "find * | sort | grep Repr")
# (find-lean4prefile "Init/Data/Repr.lean")
# (find-lean4prefile "Init/Data/Repr.lean" "def List.repr")
# (find-lean4prefile "Lean/Elab/Deriving/Repr.lean")

# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "recall that any type implementing")
# (find-lean4prefile "Lean/Elab/Deriving/Repr.lean" "def mkReprInstanceHandler")
# (find-lean4prefile "Lean/MonadEnv.lean"  "def isInductive")
# (find-lean4prefile "Lean/Structure.lean" "def getStructureFields")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'mkRepr' *")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")
set_option trace.Elab.command true

inductive myNat where
  | zero             : myNat
  | succ (n : myNat) : myNat
  deriving Repr

def my1 := myNat.succ myNat.zero
#check my1
#print my1
#eval  my1
#eval  repr my1
#check repr my1
-- #print repr my1
#check Std.Format
#synth Repr myNat
#print instReprMyNat

-- end




#####
#
# Is there a variant of repr that "prints the type"?
# 2024jun11
#
#####

# «repr-type»  (to ".repr-type")
# (to "runTermElabM")
# (to "inferType")
# (to "elab-type")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Is.20there.20a.20variant.20of.20repr.20that.20.22prints.20the.20type.22.3F/near/444131617

Is there a variant of repr that "prints the type"?

I wrote my first DSL a few days ago - here
https://github.com/edrx/LuaTreeLean , screenshot
http://anggtwu.net/LuaTreeLean/screenshot.png - and I'm in a stage in
which I still have to decompose each example in the Metaprogramming
book into 10 smaller snippets to understand what is going on in it...
and this looks like a good way to explore (specific) Syntax/TSyntax
objects:

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Elab Command

elab "#withstring " x:str : command =>
  match x with
  | `("a") => logInfo x
  | `("b") => do { logInfo x; logInfo (repr x) }
  | `("c") => do { logInfo x; logInfo (repr x.raw) }
  | _ => Elab.throwUnsupportedSyntax

#withstring "a"
#withstring "b"
#withstring "c"

-- end

I know that repr o converts o to its repr as a string, and #check o
prints o and its type - but #check is a command, so it has access to
the current context...

Is there a function that receives an object o and returns its type
converted to a string?





#####
#
# runActions
# 2024jun01
#
#####

# «runActions»  (to ".runActions")
# (to "do-notation")
# (find-fplean4doc "hello-world/running-a-program#combining-io-actions")
# (find-fplean4page 66 "Combining IO Actions")
# (find-fplean4text 66 "Combining IO Actions")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def getoutput (cmd : String) (args : Array String) : IO String := do
  let out ← IO.Process.output { cmd := cmd, args := args }
  return out.stdout

def now    := getoutput "date" #["+%S"]
def sleep1 := getoutput "sleep" #["1"]

#eval now
#eval sleep1
#eval Unit.unit

#eval now
#eval sleep1
#eval now
#eval Unit.unit
#check ()

-- end






#####
#
# runCmd
# 2024may18
#
#####

# «runCmd»  (to ".runCmd")
# «run_cmd»  (to ".run_cmd")
# (to "show-from-do")
# (to "CommandElabM")
# (to "ReaderT")
# (find-lean-links "runcmd")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'runCmd' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'executes code in' *")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "@[builtin_command_elab runCmd]")
# (find-lean4prefile "Init/Notation.lean" "The `run_cmd doSeq` command executes code in")
# (find-lean4prefile "Init/Notation.lean" "syntax (name := runCmd) \"run_cmd \" doSeq : command")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/run_cmd.2C.20monads.2C.20and.20tests.20for.20their.20methods/near/442408599
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
import Lean.Elab.Command
open   Lean.Elab.Command
open   Lean
-- set_option trace.Elab.command true
namespace Foo
run_cmd                                 logInfo (← getCurrNamespace)
#eval show  CommandElabM Unit  from  do logInfo (← getCurrNamespace)
#eval show (CommandElabM Unit) from (do logInfo (← getCurrNamespace))
#check                               do logInfo (← getCurrNamespace)
#check                                  logInfo
#check                                             getCurrNamespace
#check      CommandElabM Unit
#check      CommandElabM

#check AddMessageContext
#check MessageData
#check MonadLog
#check MonadOptions
#check logInfo

run_cmd do
  let stx <- `(fun {α β} [BEq α] (ab : α×β) => let (a,_) := ab; a==a)
  -- process stx
  Lean.logInfo m!"{stx}"

-- end




#####
#
# runParserCategory
# 2024jun12
#
#####

# «runParserCategory»  (to ".runParserCategory")
# https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Simple.20parsing.2Belaboration.20with.20metaprogramming
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean

inductive MyType
| a : MyType -> MyType
| b : MyType -> MyType
| c : MyType
deriving Inhabited, BEq, Repr

open Lean Elab

unsafe def stringToMyType (string : String) : TermElabM (Option MyType) := do
  let e ← getEnv
  let .ok syn := Parser.runParserCategory e `term string | return none
  logInfo syn
  -- we could elab here, but its not needed
  -- let expr ← Term.elabTerm syn (some (.const `MyType []))
  -- logInfo expr

  let out ← Term.evalTerm MyType (.const `MyType []) syn
  logInfo (repr out)
  return out

#eval MyType.a (.b (.a (.a .c)))
#eval stringToMyType "MyType.a (.b (.a (.a .c)))"

-- end






#####
#
# runTermElabM
# 2024jun12
#
#####

# «runTermElabM»  (to ".runTermElabM")
# (to "inferType")
# (to "repr-type")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/Is.20there.20a.20variant.20of.20repr.20that.20.22prints.20the.20type.22.3F/near/444131617
# (find-lean4prefile "Lean/Elab/Command.lean" "def runTermElabM")
# (find-lean4prefile "Lean/Elab/SyntheticMVars.lean" "def elabTermAndSynthesize")
# (find-lean4prefile "Lean/Elab/SyntheticMVars.lean" "partial def synthesizeSyntheticMVars")
# (find-lean4prefile "Lean/Meta/Basic.lean" "@[extern 6 \"lean_infer_type\"] opaque inferType")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean Elab Command Meta

elab "#my_check1 " t:term : command => do
  runTermElabM fun _ => do
    let e1 ← Term.elabTermAndSynthesize t none
    let eTy1 ← inferType e1
    logInfo m!"{e1} : {eTy1}"

elab "#my_check2 " t:term : command => do
  runTermElabM fun _ => do
    let e2 ← Term.elabTerm t none
    Term.synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := true)
    let eTy2 ← inferType e2
    logInfo m!"{e2} : {eTy2}"

#my_check1 "s"
--#my_check1 do logInfo "foo"
#my_check2   do logInfo "foo"

-- end







#####
#
# rw
# 2024mar14
#
#####

# «rw»  (to ".rw")
# (find-lean4rc1file "Init/Tactics.lean" "macro (name := rwSeq) \"rw\"")
# (find-mathsinleanpage 9 "2.1 Calculating")
# (find-mathsinleantext 9 "2.1 Calculating")
# (find-mathsinleanpage 9 "2.1 Calculating" "tactic rw")
# (find-mathsinleantext 9 "2.1 Calculating" "tactic rw")
# (find-leanmathsdoc "C02_Basics#calculating")
# (find-mathsinleanfile "MIL/C02_Basics/S01_Calculating.lean")



#####
#
# saveState
# 2024jun08
#
#####

# «saveState»  (to ".saveState")
# (find-leanmetadoc  "main/04_metam#backtracking")
# (find-leanmetadocr "main/04_metam" "## Backtracking")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean

def tryM (x : MetaM Unit) : MetaM Unit := do
  let s ← saveState
  try
    x
  catch _ =>
    restoreState s

-- end






#####
#
# scoped-syntax
# 2024may15
#
#####

# «scoped-syntax»  (to ".scoped-syntax")
# (to "check")
# (find-leanmetadoc  "main/05_syntax#free-form-syntax-declarations")
# (find-leanmetadocw "main/05_syntax#free-form-syntax-declarations")
# (find-leanmetadocr "main/05_syntax" "### Free form syntax declarations")
# (find-leanmetadocr "main/05_syntax" "namespace Playground2")
# (find-lean4prefile "Lean/Elab/Term.lean" "elaboration function for '{k}' has not been implemented")
# (find-lean4prefile "Lean/Elab/Command.lean" "elaboration function for '{k}' has not been implemented")



#####
#
# semi-output
# 2024jun22
#
#####

# «semi-output»  (to ".semi-output")
# (find-lean4prefile "Init/Prelude.lean" "Gadget for marking semi output parameters")



#####
#
# server
# 2024jun01
#
#####

# «server»  (to ".server")
# (to "import-problem")
# (to "trace.Elab.info")
# (find-lean4prefile "Lean/Server.lean")
# (find-lean4prefile "Lean/Server/")
# (find-lean4prefile "Lean/Server/Completion.lean" "Search namespaces")
# (find-lean4prefile "Lean/Server/README.md")
# (find-lean4prefile "Lean/Server/README.md" "cannot import a `.lean` file without compiling it first")
# (find-lean4prefile "Lean/Server/README.md" "lake setup-file")
# (find-lean4prefile "Lean/Server/README.md" "set_option trace.Elab.info true")




#####
#
# show
# 2024mar22
#
#####

# «show»  (to ".show")
# (to "from-do")
# (find-lean-links "show")
# (find-tpil4file "propositions_and_proofs.md" "show p from hp")
# (find-tpil4page 25 "show p from hp")
# (find-tpil4text 25 "show p from hp")
# (find-lean4prefile "Init/Prelude.lean" "`show T' from e` is sugar for")
# (find-lean4prefile "Init/Tactics.lean" "`show t` finds the first goal")

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")
#check show Int from 42
#check show Nat from 42
-- end

# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")
set_option trace.Elab.command true

variable {P : Prop}
variable {Q : Prop}
theorem t1 : P → Q → P :=
  fun p : P =>
  fun q : Q =>
  show P from p

theorem t1 : P → Q → P := fun p : P => fun q : Q => show P from p

theorem t0 : P → P := fun p : P => show P from p

theorem t0a : P → P := fun p : P => show P from p
theorem t0b : P → P := fun p : P =>             p

#check fun p : P => show P from p

#check show Int from 42

#check fun p : P => show P from p
#check fun p : P =>             p
#check show Int from 42

-- end



#####
#
# show ... from do ...
# 2024may21
#
#####

# «show-from-do»  (to ".show-from-do")
# (to "Id.run")
# (to "show")
# (find-lean4prefile "Init/Prelude.lean" "`show T' from e` is sugar for")
# (find-lean-links "from do")
# (find-lean-links "from")
# (find-leanmetadocrgrep "grep --color=auto -nRH --null -e 'from do' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'from do' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"from \"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" from \"' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e from * | grep -a do")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '«from\ »' *")
# (find-leanmetadoc  "main/04_metam#basic-operations")
# (find-leanmetadocr "main/04_metam" "### Basic Operations")
# (find-leanmetadocr "main/04_metam" "### Basic Operations" "#eval show MetaM Unit from do")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

instance : Monad List  where
  pure := List.pure
  bind := List.bind

#check                    do return 42   -- _ : ?m   Nat
#check show IO   Nat from do return 42   -- _ : IO   Nat
#check show List Nat from do return 42   -- _ : List Nat
#check show List Int from do return 42   -- _ : List Int

-- end





#####
#
# sleep1 and friends
# 2024jun02
#
#####

# «sleep1»  (to ".sleep1")
# (to "do-notation")
# (to "pp.notation")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def getoutput  (cmd : String) (args : List String) : IO String := do
  let out ← IO.Process.output { cmd := cmd, args := args.toArray }
  return out.stdout

def getoutput0 (cmd : String) (args : List String) : IO Unit   := do
  let _   ← IO.Process.output { cmd := cmd, args := args.toArray }
  return

def duplicate (str : String) : IO String := getoutput  "echo"  [str, str]
def seconds                  : IO String := getoutput  "date"  ["+%S"]
def sleep1                   : IO Unit   := getoutput0 "sleep" ["1"]

#eval  getoutput "echo" ["a", "b"]
#eval  duplicate "abc"
#eval  seconds
#check sleep1

#eval do IO.println (← seconds)

def ss := do
  let a ← seconds
  sleep1
  let b ← seconds
  return a++b

#check ss
#eval  ss
#print ss
set_option pp.notation false in
#print ss

-- end



#####
#
# specialize
# 2024jun01
#
#####

# «specialize»  (to ".specialize")
# (find-lean-links "specialize")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'specialize' *")



#####
#
# State
# 2024jun22
#
#####

# «State»  (to ".State")
# (find-es "haskell" "wikibook")
# https://en.wikibooks.org/wiki/Haskell/Understanding_monads/State
# (find-lean4prefile "Init/Control/State.lean" "instance : Monad (StateT σ m) where")
# (find-lean-links "State")
# (find-fplean4doc "monad-transformers/transformers#state")
# (find-fplean4page 262 "def StateT ")
# (find-fplean4text 262 "def StateT ")
# (find-lean4prefile "Init/Prelude.lean" "class MonadState ")
# (find-lean4prefile "Init/Control/State.lean" "def StateT ")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

structure LetterCounts where
  vowels : Nat
  consonants : Nat
deriving Repr

inductive Err where
  | notALetter : Char → Err
deriving Repr

def vowels :=
  let lowerVowels := "aeiuoy"
  lowerVowels ++ lowerVowels.map (·.toUpper)

def consonants :=
  let lowerConsonants := "bcdfghjklmnpqrstvwxz"
  lowerConsonants ++ lowerConsonants.map (·.toUpper )

def countLetters (str : String) : StateT LetterCounts (Except Err) Unit :=
  let rec loop (chars : List Char) := do
    match chars with
    | [] => pure ()
    | c :: cs =>
      let st ← get
      let st' ←
        if c.isAlpha then
          if vowels.contains c then
            pure {st with vowels := st.vowels + 1}
          else if consonants.contains c then
            pure {st with consonants := st.consonants + 1}
          else -- modified or non-English letter
            pure st
        else throw (.notALetter c)
      set st'
      loop cs
  loop str.toList

-- end



# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check StateM
#check StateM Nat
#check StateM Nat Nat
#check StateT
#check StateT Nat
#check StateT Nat List
#check StateT Nat List Nat

#check StateT.get
#check StateT.bind

#check      StateM
#check      StateM Nat
#check      StateM Nat Nat
#check show StateM Nat Nat from do return 42
#check show StateM Nat Nat from do return (← get)

-- end






#####
#
# Std.Format
# 2024may17
#
#####

# «Std.Format»  (to ".Std.Format")
# (to "coercion")
# (find-lean4prefile "Init/Data/Format/Basic.lean" "inductive Format")
# (find-lean4prefile "Init/Data/Format/Basic.lean" "Wadler's" "A Prettier Printer")
# (find-lean4prefile "Init/Data/Format/Basic.lean" "instance : Coe String Format := ⟨text⟩")
# (find-lean4prefile "Init/Data/Format/Basic.lean" "class ToFormat (α : Type u) where")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Init.Data.Format
#check Std.Format.isEmpty
#check Std.Format.paren
open   Std.Format
open   Std

#check Format
#check line
#check text
#check        text "ab"
#check paren (text "ab")
#check ( "ab" : Format)
#check (("ab" : String) : Format)
#eval paren "ab"

#eval nest 2 <| "."   ++ align true  ++ "a" ++ line ++ "b"
#eval nest 2 <| "..." ++ align true  ++ "a" ++ line ++ "b"
#eval nest 2 <| "..." ++ align false ++ "a" ++ line ++ "b"   -- ?
#eval nest 4 <| "..." ++ align true  ++ "a" ++ line ++ "b"

def pile : (List Format) → Format
  | []           => ""
  | [item]       => item
  | item :: rest => item ++ line ++ pile rest

def zpile (head : String) (fmts : List Format) :=
  nest (1 + String.length head) <| head ++ align true ++ (pile fmts)

#eval  pile       ["b", "c"]
#eval zpile "a"   ["b", "c"]
#eval zpile "aaa" ["b", "c"]
#eval zpile "aaa" ["b", "c", zpile "d" ["e", "f"]]

-- end





#####
#
# s!"str" and m!"str"
# 2024mar23
#
#####

# «string-interpolation»  (to ".string-interpolation")
# (to "interpolatedStr")
# (find-fplean4page 59 "String Interpolation")
# (find-fplean4text 59 "String Interpolation")
# (find-fplean4page 106 "when a value occurs in an interpolated string")
# (find-fplean4text 106 "when a value occurs in an interpolated string")
# (find-fplean4doc "getting-to-know/conveniences")
# (find-fplean4doc "getting-to-know/conveniences#string-interpolation")
# (find-fplean4doc "type-classes/pos#conversion-to-strings")
# (find-fplean4doc "type-classes/pos#conversion-to-strings" "in an interpolated string")




#####
#
# structures
# 2023jun24
#
#####

# «structure»  (to ".structure")
# «structures»  (to ".structures")
# (to "coercion")
# (to "Repr")
# (find-fplean4page 18 "Structures")
# (find-fplean4text 18 "Structures")
# (find-fplean4page 20 "structure Point3D where")
# (find-fplean4text 20 "structure Point3D where")
# (find-fplean4page 23 "To override a structure's constructor name" "two colons")
# (find-fplean4text 23 "To override a structure's constructor name" "two colons")
# (find-fplean4page 24 "The function Point.modifyBoth")
# (find-fplean4text 24 "The function Point.modifyBoth")
# (find-fplean4doc "getting-to-know/structures")
# (find-fplean4doc "getting-to-know/structures#updating-structures")

# (find-tpil4page 106 "structure Prod")
# (find-tpil4text 106 "structure Prod")
# (find-tpil4page 152 "Declaring Structures")
# (find-tpil4text 152 "Declaring Structures")
# (find-tpil4doc  "inductive_types#constructors-with-arguments")
# (find-tpil4docr "inductive_types" "Constructors with Arguments")
# (find-tpil4docr "inductive_types" "structure Prod")
# (find-tpil4doc  "structures_and_records")
# (find-tpil4doc  "structures_and_records#declaring-structures")
# (find-tpil4docr "structures_and_records" "Declaring Structures")

# (find-anggfile "LEAN/structures1.lean")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

structure Point where
  x : Float
  y : Float
deriving Repr

def     p45 : Point := { x := 4, y := 5 }
#eval   p45
#eval { p45 with y := 6 }

#check Point.mk
#check Point.x
#check Point.y

structure Point3D where
  x : Float
  y : Float
  z : Float
deriving Repr

def origin3D : Point3D := { x := 0.0, y := 0.0, z := 0.0 }

--#check { x := 0.0, y := 0.0 }           -- err
#check  ({ x := 0.0, y := 0.0 } : Point)
#check   { x := 0.0, y := 0.0   : Point}

-- end




#####
#
# structure-like
# 2024jun02
#
#####

# «structure-like»  (to ".structure-like")
# (find-lean4prefile "Lean/Expr.lean" "must be an structure-like inductive type. That is")



#####
#
# stx
# 2024jun13
#
#####

# «stx»  (to ".stx")
# (find-lean4prefile "Init/Notation.lean" "  | `(stx| $p +) => `(stx| many1($p))")





#####
#
# syntax (command)
# 2024jun08
#
#####

# «syntax-command»  (to ".syntax-command")
# (find-leanmetadoc  "main/05_syntax#free-form-syntax-declarations")
# (find-leanmetadocr "main/05_syntax" "### Free form syntax declarations")
# (find-leanmetadocr "main/05_syntax"   "add a new" "syntax rule to an already existing")
# (find-leanmetadocr "main/05_syntax"   "syntax \"[Bool|\" boolean_expr \"]\" : term")
# (find-leanmetadoc  "main/05_syntax#constructing-new-syntax")
# (find-leanmetadocr "main/05_syntax" "### Constructing new `Syntax`")
# (find-leanmetadoc  "main/05_syntax#matching-on-syntax")
# (find-leanmetadocr "main/05_syntax" "### Matching on `Syntax`")
# (find-leanmetadoc  "main/05_syntax#typed-syntax")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check Lean.Parser.Category
#print Lean.Parser.Category
#check Lean.Parser.Category.boolean_expr
declare_syntax_cat          boolean_expr
#check Lean.Parser.Category.boolean_expr

syntax "⊥" : boolean_expr
syntax "⊤" : boolean_expr
syntax:40 boolean_expr " OR "  boolean_expr : boolean_expr
syntax:50 boolean_expr " AND " boolean_expr : boolean_expr

syntax "[Bool|" boolean_expr "]" : term
#check_failure [Bool| ⊥ AND ⊤]

syntax binOne     := "O"
syntax binZero    := "Z"
syntax binDigit   := binZero <|> binOne
syntax binNumber  := binDigit,+
syntax binNumber' := binDigit,*
syntax "emptyBin(" binNumber' ")" : term
#check_failure emptyBin()

syntax "binCompact(" ("Z" <|> "O"),+ ")" : term
#check_failure binCompact(Z, O, Z, Z, O)

syntax "binDoc(" (str ";")? binNumber ")" : term
#check_failure binDoc(Z, O, Z, Z, O)
#check_failure binDoc("mycomment"; Z, O, Z, Z, O)

open Lean

def isAdd11 : Syntax → Bool
  | `(Nat.add 1 1) => true
  | _ => false

def isAdd : Syntax → Option (Syntax × Syntax)
  | `(Nat.add $x $y) => some (x, y)
  | _ => none

#eval isAdd11 (Syntax.mkApp (mkIdent `Nat.add) #[Syntax.mkNumLit "1", Syntax.mkNumLit "1"])
#eval isAdd11 (Syntax.mkApp (mkIdent `Nat.add) #[mkIdent `foo,        Syntax.mkNumLit "1"])
#eval isAdd   (Syntax.mkApp (mkIdent `Nat.add) #[Syntax.mkNumLit "1", Syntax.mkNumLit "1"])
#eval isAdd   (Syntax.mkApp (mkIdent `Nat.add) #[mkIdent `foo,        Syntax.mkNumLit "1"])
#eval isAdd   (Syntax.mkApp (mkIdent `Nat.add) #[mkIdent `foo])

-- end







#####
#
# syntax (parser)
# 2024may23
#
#####

# «syntax-parser»  (to ".syntax-parser")
# (find-lean-links "syntax")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'syntax' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\"syntax \"' *")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "@[builtin_command_parser] def «syntax»")




#####
#
# syntax (name := bla) ...
# 2024may23
#
#####

# «syntax-name»  (to ".syntax-name")
# (find-lean-links "syntax")
# (find-leanmetadoc  "main/02_overview#3-essential-commands-and-their-syntax-sugars")
# (find-leanmetadocr "main/02_overview" "## 3 essential commands and their syntax sugars")
# (find-leanmetadoc  "main/05_syntax")
# (find-leanmetadocr "main/05_syntax")
# (find-leanmetadoc  "main/07_elaboration")
# (find-leanmetadocr "main/07_elaboration")
# (find-lean4pregrep "grep --color=auto -nRH --null -e syntax * | grep -a name")
# (find-leanmetadocrgrep "grep --color=auto -nRH --null -e 'syntax (name' *")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "@[builtin_command_parser] def «syntax»")
# (find-lean4prefile "Lean/Parser/Syntax.lean" "def namedName := leading_parser")
# (find-lean4prefile "Lean/Elab/Command.lean" "abbrev CommandElab")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Elab Command

syntax (name := xxx) "red"   : command
syntax (name := yyy) "green" : command
syntax (name := zzz) "blue"  : command

@[macro xxx]        def redMacro   : Macro := λ stx => match stx with | _ => `(green)
@[macro yyy]        def greenMacro : Macro := λ stx => match stx with | _ => `(blue)
@[command_elab zzz] def blueElab   : CommandElab := λ _ => Lean.logInfo "finally, blue!"

red  -- finally, blue!

-- end




#####
#
# #synth
# 2024may31
#
#####

# «synth»  (to ".synth")
# (to "leading_parser")
# (to "Repr")
# (to "deriving")
# (find-lean-links "#synth")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/leading_parser.3F
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def synth")
# (find-lean4prefile "Lean/Elab/BuiltinCommand.lean" "@[builtin_command_elab «synth\ »] def elabSynth")
# (find-lean4pregrep "grep --color=auto -nRHw --null -e 'synth' *")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

set_option trace.Elab.command true

inductive myNat where
  | zero             : myNat
  | succ (n : myNat) : myNat
  deriving Repr

#synth Repr myNat
#print instReprMyNat

-- end




#####
#
# #tactic_expand1
# 2024jun23
#
#####

# «tactic_expand1»  (to ".tactic_expand1")
# https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/.E2.9C.94.20see.20result.20of.20tactic.20macro/near/446310888
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open   Lean

elab "#tactic_expand1 " t:tactic : command => do
  let some t ← Elab.liftMacroM <| Lean.Macro.expandMacro? t | logInfo m!"Not a macro"
  logInfo m!"{t}"

#tactic_expand1 exists 1
-- (refine ⟨1, ?_⟩; try trivial)

-- end




#####
#
# tagged-subgoals
# 2024apr30
#
#####

# «tagged-subgoals»  (to ".tagged-subgoals")
# (find-tpil4page  55 "5. Tactics")
# (find-tpil4text  55    "Tactics")
# (find-tpil4page  57    "tagged the first subgoal as left")
# (find-tpil4text  57    "tagged the first subgoal as left")
# (find-tpil4doc  "tactics#entering-tactic-mode")
# (find-tpil4docr "tactics" "Entering Tactic Mode")
# (find-tpil4docr "tactics" "Entering Tactic Mode" "tagged the first subgoal as")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

variable (P Q R : Prop)
variable {P Q R : Prop}
variable {p : P}
variable {q : Q}

example    (p : P) (q : Q) : P ∧ Q := And.intro p q
#check fun (p : P) (q : Q)         => And.intro p q

-- end







#####
#
# telescopes
# 2024apr27
#
#####

# «telescopes»  (to ".telescopes")
# (find-angg "LEAN/telescopes1.lean")
# (find-leanmetadoc  "main/04_metam#deconstructing-expressions")
# (find-leanmetadocr "main/04_metam" "### Deconstructing Expressions")
# (find-leanmetadocr "main/04_metam" "forallTelescope")
# (find-lean-links "telescope")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'telescope' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'telescope' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'foralltelescope' *")




#####
#
# termination
# 2024jun06
#
#####

# «termination»  (to ".termination")
# (to "partial")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'failed to show' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'fail to show' *")
# (find-fplean4page 31 "fail to show termination for")
# (find-fplean4text 31 "fail to show termination for")
# (find-fplean4-links "termination")
# (find-fplean4docrgrep "grep --color=auto -nRH --null -e 'termination' *")
# (find-fplean4docrgrep "grep --color=auto -nRH --null -e 'termination_by' *")
# (find-fplean4doc  "programs-proofs/summary")
# (find-fplean4doc  "programs-proofs/summary#proving-termination")
# (find-fplean4docr "programs-proofs/summary" "## Proving Termination")
# (find-fplean4docr "programs-proofs/summary" "## Proving Termination" "A good way")

"A good way to write recursive functions is to begin by declaring them
`partial` and debugging them with testing until they return the right
answers. Then, `partial` can be removed and replaced with a
`termination_by` clause."

fail to show termination for
  LuaTree.toLua
with errors
structural recursion cannot be used

failed to prove termination, possible solutions:
  - Use `have`-expressions to prove the remaining goals
  - Use `termination_by` to specify a different well-founded relation
  - Use `decreasing_by` to specify your own tactic for discharging this kind of goal




#####
#
# termParser
# 2024may15
#
#####

# «termParser»  (to ".termParser")
# (find-lean4prefile "Lean/Parser/Basic.lean" "def termParser")
# (find-lean4prefile "Lean/Parser/Basic.lean" "def termParser (prec : Nat := 0) : Parser :=")
# (find-lean4prefile "Lean/Parser/Basic.lean" "def categoryParser")




#####
#
# theorem
# 2024mar27
#
#####

# «theorem»  (to ".theorem")
# (find-fplean4doc "props-proofs-indexing#propositions-and-proofs")
# (find-fplean4doc "props-proofs-indexing#propositions-and-proofs" "theorem keyword instead of def")
# (find-tpil4doc  "propositions_and_proofs")
# (find-tpil4doc  "propositions_and_proofs#working-with-propositions-as-types")
# (find-tpil4docr "propositions_and_proofs" "Working with Propositions as Types")
# (find-tpil4docr "propositions_and_proofs" "``theorem`` command")
# (find-tpil4page 25 "the theorem command")
# (find-tpil4text 25 "the theorem command")
# (find-lean4prefile "Init/Tactics.lean" "This simp theorem")
# (find-lean4prefile "Lean/Meta/Tactic/Simp/SimpCongrTheorems.lean" "with the `congr` attribute")
# (find-lean4prefile "Lean/Elab/DefView.lean" "leading_parser \"theorem \"")
# (find-lean4prefile "Lean/Elab/Declaration.lean" "Lean.Parser.Command.theorem")
# (find-lean4prefile "Lean/Elab/Tactic/Simp.lean" "using the simp theorems collected in `ctx`")
# (find-lean4prefile "Lean/Parser/Command.lean" "def «theorem»")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

variable (P Q R : Prop)
variable {P Q R : Prop}

theorem t1a : P → P := fun p : P =>             p
theorem t1b : P → P := fun p : P => show P from p
theorem t1c               (p : P)      : P   := p

#print t1a           -- p → q → p
#print t1b           -- p → q → p
#print t1c           -- p → q → p

theorem ta (p : P) (q : Q) : P ∧ Q := And.intro p q
example    (p : P) (q : Q) : P ∧ Q := And.intro p q
#check fun (p : P) (q : Q)         => And.intro p q
#check fun (p : P) (q : Q)         =>
  let paq := And.intro p q
  paq

-- end





#####
#
# toolchains
# 2024may12
#
#####

# «toolchains»  (to ".toolchains")
# (to "metaprogramming-toolchain")
# (find-fline "~/.elan/toolchains/")
# (code-c-d "elantoolchains" "~/.elan/toolchains/")
# (find-elantoolchainsfile "")
# (find-elantoolchainssh "du -ch")
# https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Update.20toolchain



#####
#
# ToString
# 2024may22
#
#####

# «ToString»  (to ".ToString")
# (to "match-bar")
# (find-fplean4page 106 "ToString")
# (find-fplean4text 106 "ToString")
# (find-fplean4doc "type-classes/pos#conversion-to-strings")
# (find-lean4presh "find * | sort | grep -i tostring")
# (find-lean4prefile "Init/Data/ToString.lean")
# (find-lean4prefile "Init/Data/ToString/Basic.lean")
# (find-lean4prefile "Init/Data/ToString/Macro.lean")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check toString  42
#eval  toString  42
#check toString "42"
#eval  toString "42"

inductive N where
  | z         : N
  | s (n : N) : N
  deriving Repr

open N

#check s (s z)
#eval  s (s z)

def N.tos
  | z   => "z"
  | s n => "s" ++ n.tos

#check (s (s z)).tos
#eval  (s (s z)).tos

instance : ToString N := ⟨N.tos⟩

#check toString (s (s z))
#eval  toString (s (s z))

-- end




#####
#
# TPiL: exercises on p.38
# 2024jun22
#
#####

# «tpil-p38»  (to ".tpil-p38")
# (find-tpil4doc "propositions_and_proofs#examples-of-propositional-validities")
# (find-tpil4page 37 "Exercises" "Prove the following identities")
# (find-tpil4text 37 "Exercises" "Prove the following identities")
# (find-tpil4page 38 "-- commutativity of ∧ and ∨")
# (find-tpil4text 38 "-- commutativity of ∧ and ∨")
# (find-tpil4page 38 "example : p ∧ q ↔ q ∧ p := sorry")
# (find-tpil4text 38 "example : p ∧ q ↔ q ∧ p := sorry")
# (find-lean4prefile "Init/Core.lean" "structure Iff")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '↔' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" ↔ \"' *")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

variable (P Q R : Prop)

-- commutativity of ∧ and ∨
theorem tc1 : P ∧ Q ↔ Q ∧ P := sorry
theorem tc2 : P ∨ Q ↔ Q ∨ P := sorry

-- associativity of ∧ and ∨
theorem ta1 : (P ∧ Q) ∧ R ↔ P ∧ (Q ∧ R) := sorry
theorem ta2 : (P ∨ Q) ∨ R ↔ P ∨ (Q ∨ R) := sorry

-- distributivity
theorem td1 : P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := sorry
theorem td2 : P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) := sorry

-- other properties
theorem top1 : (P → (Q → R)) ↔ (P ∧ Q → R) := sorry
theorem top2 : ((P ∨ Q) → R) ↔ (P → R) ∧ (Q → R) := sorry
theorem top3 : ¬(P ∨ Q) ↔ ¬P ∧ ¬Q := sorry
theorem top4 : ¬P ∨ ¬Q → ¬(P ∧ Q) := sorry
theorem top5 : ¬(P ∧ ¬P) := sorry
theorem top6 : P ∧ ¬Q → ¬(P → Q) := sorry
theorem top7 : ¬P → (P → Q) := sorry
theorem top8 : (¬P ∨ Q) → (P → Q) := sorry
theorem top9 : P ∨ false ↔ P := sorry
theorem top10 : P ∧ False ↔ False := sorry
theorem top11 : (P → Q) → (¬Q → ¬P) := sorry

-- end
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

variable (P Q R : Prop)

theorem tc1 : P ∧ Q ↔ Q ∧ P :=
  let a : P ∧ Q → Q ∧ P :=
    fun b : P ∧ Q =>
      let c : P := b.1
      let d : Q := b.2
      let e : Q ∧ P := ⟨d,c⟩
      e
  let f : Q ∧ P → P ∧ Q :=
    fun g : Q ∧ P =>
      let h : Q := g.1 
      let i : P := g.2
      let j : P ∧ Q := ⟨i,h⟩
      j
  ⟨a,f⟩

#print  tc1
#reduce tc1

-- end






#####
#
# trace.Elab.command
# 2024jun08
#
#####

# «trace.Elab.command»  (to ".trace.Elab.command")
# (find-esgrep "grep --color=auto -niH --null -e trace.Elab.command lean.e")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

set_option trace.Elab.command true in
declare_syntax_cat ltsyntax

-- end

# (find-lean-links "trace")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'trace' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" trace \"' *")




#####
#
# trace.Elab.info
# 2024jun10
#
#####

# «trace.Elab.info»  (to ".trace.Elab.info")
# (to "server")






#####
#
# try-catch
# 2024may12
#
#####

# «try-catch»  (to ".try-catch")
# (to "exceptions")
# (find-leanmetadoc  "main/01_intro#building-a-command")
# (find-leanmetadocr "main/01_intro" "### Building a command")
# (find-lean4prefile "Lean/CoreM.lean" "try-catch")
# (find-lean4prefile "Lean/Elab/Do.lean" "def doTry :=")
# (find-lean4pregrep "grep --color=auto -nRH --null -e catch *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'catch \"' *")
# (find-fplean4doc )
# (find-fplean4page 261 "def divFrontend")
# (find-fplean4text 261 "def divFrontend")
# (find-fplean4doc "monad-transformers/transformers#type-classes-for-exceptions")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

def ab [Monad m] [MonadExcept Nat m] : m String :=
  try          pure "a"
  catch | _ => pure "b"

#print ab

-- end





#####
#
# TSyntax
# 2024jun02
#
#####

# «TSyntax»  (to ".TSyntax")
# (to "checksyntax-test")
# (to "mkSyntaxQuotation")
# (find-lean4prefile "Init/Prelude.lean" "structure TSyntax")
# (find-leanmetagrep "grep --color=auto -nRH --null -e TSyntax *")
# (find-leanmetadoc  "main/05_syntax")
# (find-leanmetadocr "main/05_syntax")
# (find-leanmetadoc  "main/06_macros")
# (find-leanmetadocr "main/06_macros")
# (find-leanmetadoc  "main/07_elaboration")
# (find-leanmetadocr "main/07_elaboration")
# (find-leanmetadoc  "extra/03_pretty-printing")
# (find-leanmetadocr "extra/03_pretty-printing")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'mainModule' *")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'addMacroScope' *")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'mkInfoFromRefPos' *")
# (find-lean4pregrep "grep --color=auto -nwRH --null -e 'TSyntax' * | grep -a instance")
# (find-lean4prefile "Init/Prelude.lean" "pure (Lean.addMacroScope mainModule n scp)")
# (find-lean4prefile "Init/Prelude.lean" "@[inline] def MonadQuotation.addMacroScope")
# (find-lean4prefile "Lean/Elab/Quotation.lean" "def stxQuot.expand (stx : Syntax) : TermElabM Syntax")
# (find-lean4prefile "Lean/Elab/Quotation.lean" "def mkSyntaxQuotation")
# (find-lean4prefile "Lean/Elab/Quotation.lean" "def mkSyntaxQuotation" "@TSyntax.mk")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

#check Lean.MonadRef.mkInfoFromRefPos
#check Lean.getCurrMacroScope
#check Lean.getMainModule
#check Lean.Syntax.atom
#check Lean.Syntax.node1
#check Lean.Syntax.node3
#check Lean.TSyntax

import Lean
open Lean Elab Command

#check                            TSyntax.mk
#check                            TSyntax.mk Syntax.missing
#check    show TSyntax `term from TSyntax.mk Syntax.missing
def ts := show TSyntax `term from TSyntax.mk Syntax.missing
#check ts
#eval  ts
#eval  ts.raw

def foo1                        (ts : TSyntax ks) : Nat := 42
def foo2 {ks : SyntaxNodeKinds} (ts : TSyntax ks) : Nat := 42
def foo3 {ks : SyntaxNodeKinds} (ts : TSyntax ks) : SyntaxNodeKinds := ks
def foo4 {ks : SyntaxNodeKinds} (ts : TSyntax ks) : Syntax := ts.raw

#check @foo1
#check @foo2
#eval  foo1 ts
#eval  foo3 ts
#eval  foo4 ts

elab "#withstring " x:str : command =>
  match x with
  | `("a")       => logInfo x
  | `("b")       => do { logInfo x; logInfo (repr x) }
  | `("c")       => do { logInfo x; logInfo (repr x.raw) }
  | _ => Elab.throwUnsupportedSyntax

#withstring "a"
#withstring "b"
#withstring "c"

def c := Lean.Syntax.node
 (Lean.SourceInfo.none)
 `str
  #[Lean.Syntax.atom
  (Lean.SourceInfo.original "".toSubstring { byteIdx := 317 } "\n\n".toSubstring { byteIdx := 320 })
  "\"c\""]

-- end




#####
#
# typeclass-seach
# 2024jun22
#
#####

# «typeclass-seach»  (to ".typeclass-seach")
# (to "class")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/How.20does.20Lean.20.22synthesize.22.20a.20.22get.22.20inside.20a.20.22do.22.3F
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'typeclass' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'typeclass search' *")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'typeclass inference' *")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

class Cla (α : Type) where met : String

instance : Cla String where met := "(string)"
instance : Cla Bool   where met := "(bool)"
instance : Cla Nat    where met := "(nat)"
instance : Cla Int    where met := "(int)"

def foo {α : Type} [inst : Cla α] (_ : α) : String := inst.met

#eval foo true
#eval foo   42
#eval foo (-42)
#eval foo "abc"

-- end
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

set_option linter.unusedVariables false

def foo1 [Monad m] [MonadState σ m]
         (a : Nat) : m Nat := do
  let xxxxxxxx := "--delimiter--"
  let b ← get      -- ok
  return a

def foo2 [Monad m] -- [MonadState σ m]
         (a : Nat) : m Nat := do
  let xxxxxxxx := "--delimiter--"
  let b ← get      -- error: failed to synthesize...
  return a

def foo3 [inst1 : Monad m] [inst2 : MonadState σ m]
         (a : Nat) : m Nat := do
  let xxxxxxxx := "--delimiter--"
  let b ← get      -- ok
  let c ← inst2.get -- same as b
  return _

-- end




#####
#
# typeof
# 2024may05
#
#####

# «typeof»  (to ".typeof")
# (find-lean-links "typeof")
# (find-lean4pregrep "grep --color=auto -niRH --null -e 'typeof' *")

def foo1 {A : _} (a : A) := a
def foo2 {A : _} (_ : A) := A
#check foo1 42
#check foo2 42





#####
#
# underscore
# 2024apr06
#
#####

# «underscore»  (to ".underscore")
# (find-tpil4page 36 "you can use an underscore _")
# (find-tpil4text 36 "you can use an underscore _")
# (find-tpil4page 21 "holes")
# (find-tpil4text 21 "holes")
# (find-tpil4page 87 "replaced by @t _")
# (find-tpil4text 87 "replaced by @t _")
# (find-tpil4page 87 "unicode brackets")
# (find-tpil4text 87 "unicode brackets")
# (find-tpil4doc  "propositions_and_proofs#examples-of-propositional-validities")
# (find-tpil4docr "propositions_and_proofs" "Examples of Propositional Validities")
# (find-tpil4docr "propositions_and_proofs" "you can use" "an underscore ``_``")
# (find-lean4grep "grep --color=auto -nRH --null -e 'synthesize placeholder' *")
# (find-lean4file "src/Lean/Elab/Term.lean" "synthesize placeholder")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

variable (P Q R : Prop)
theorem triv1 (p : P) : P := p
theorem triv2 («.P» : P) : P := «.P»
theorem triv3 («.P» : P) («P→Q» : P → Q) : Q := _
theorem triv4 («.P» : P) («P→Q» : P → Q) : Q := «P→Q» _
theorem triv5 («.P» : P) («P→Q» : P → Q) : Q := «P→Q» «.P»

-- end






#####
#
# variable
# 2024mar15
#
#####

# «variable»  (to ".variable")
# (find-lean-links "the ``variable`` command")
# (find-tpil4doc  "dependent_type_theory")
# (find-tpil4doc  "dependent_type_theory#variables-and-sections")
# (find-tpil4docr "dependent_type_theory" "# Variables and Sections")
# (find-tpil4docr "dependent_type_theory" "the ``variable`` command")
# (find-tpil4doc  "dependent_type_theory#implicit-arguments")
# (find-tpil4docr "dependent_type_theory" "Implicit Arguments")
# (find-tpil4docr "dependent_type_theory" "can also be specified as implicit")
# (find-tpil4doc  "propositions_and_proofs")
# (find-tpil4doc  "propositions_and_proofs#disjunction")
# (find-tpil4docr "propositions_and_proofs" "### Disjunction")
# (find-tpil4docr "propositions_and_proofs" "variable (p q r : Prop)")
# (find-tpil4docr "propositions_and_proofs" "variable {p : Prop}")
# (find-lean4doc      "sections")
# (find-lean4docrfile "sections.md" "``variable``")
# (find-lean4docrfile "sections.md" "``section``")
# (find-lean4prefile "Lean/Parser/Command.lean" "@[builtin_command_parser] def «variable»")
# (find-lean4prefile "Lean/Meta/ExprTraverse.lean" "variable {M} [Monad M] [MonadLiftT MetaM M]")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/I.20accidentally.20proved.202.3D3



#####
#
# #where
# 2024may18
#
#####

# «where»  (to ".where")
# (to "getCurrNamespace")
# (find-lean-links "#where")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '#where' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e 'where' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '«where»' *")
# (find-lean4pregrep "grep --color=auto -nRH --null -e '\" #where \"' *")
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/A.20command.20that.20prints.20the.20current.20namespace.3F/near/439330480
# (find-sh "lean")
# (find-sh "lean --version")
# (find-lean4prefile "")




#####
#
# whnf
# 2024may28
#
#####

# «whnf»  (to ".whnf")
# (to "reduce")
# (find-leanmetadoc  "main/04_metam#weak-head-normalisation")
# (find-leanmetadocr "main/04_metam" "### Weak Head Normalisation")
# (ee-copy-rest-3m nil "-- end" "/tmp/L/a.lean")

import Lean
open Lean Lean.Expr Lean.Meta

open Lean.Elab.Term in
def whnf' (e : TermElabM Syntax) : TermElabM Format := do
  let e ← elabTermAndSynthesize (← e) none
  ppExpr (← whnf e)

#eval whnf' `(List.cons 1 [])
#eval whnf' `(List.cons (1 + 1) [])
#eval withTransparency .reducible $ whnf' `(List.append [1] [2])
#eval whnf' `(λ x : Nat => x)
#eval whnf' `(∀ x, x > 0)
#eval whnf' `(Type 3)
#eval whnf' `((15 : Nat))
#eval whnf' `(List.append [1])
#eval whnf' `((λ x y : Nat => x + y) 1)
#eval whnf' `(let x : Nat := 1; x)

def matchAndReducing (e : Expr) : MetaM (Option (Expr × Expr)) := do
  match ← whnf e with
  | (.app (.app (.const ``And _) P) Q) => return some (P, Q)
  | _ => return none

def matchAndReducing₂ (e : Expr) : MetaM (Option (Expr × Expr × Expr)) := do
  match ← whnf e with
  | (.app (.app (.const ``And _) P) e') =>
    match ← whnf e' with
    | (.app (.app (.const ``And _) Q) R) => return some (P, Q, R)
    | _ => return none
  | _ => return none

-- end






#####
#
# delaborator-diagram
# 2024mar10
#
#####

# «delaborator-diagram»  (to ".delaborator-diagram")
# https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Pretty-printing.20of.20sums/near/355279588
# https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Pretty-printing.20of.20sums/near/355262783
#
# String ---(parser)---> Syntax ---(elaborator)---> Expr ---(delaborator)---> Syntax ---(formatter)---> String
#
#         parser           elaborator         delaborator           formatter
# String --------> Syntax ------------> Expr -------------> Syntax -----------> String







#####
#
# reference-manual
# 2024mar09
#
#####

# «reference-manual»  (to ".reference-manual")
# «:leanref»                       (to ".:leanref")
# (find-angg ".emacs.lean.el" "ee-rstdoc-:leanref")
# https://leanprover.github.io/reference/
# (find-leanrefdoc  "using_lean#using-lean-with-emacs")
# (find-leanrefdocw "using_lean#using-lean-with-emacs")
# (find-leanrefdocw "declarations")

# (code-c-d "leanrefdoc" "$S/https/leanprover.github.io/reference/")
# (find-leanrefdocfile "")
# (find-leanrefdocfile "_sources/")

# (find-leanrefdocfile "")
# https://leanprover.github.io/reference/lean_reference.pdf
(code-pdf-page "leanref" "$S/https/leanprover.github.io/reference/lean_reference.pdf")
(code-pdf-text "leanref" "$S/https/leanprover.github.io/reference/lean_reference.pdf")
;; (find-leanrefpage)
;; (find-leanreftext)




#####
#
# metaprogramming
# 2024mar09
#
#####

# «metaprogramming»  (to ".metaprogramming")
# «:leanmeta»              (to ".:leanmeta")
# (find-angg ".emacs"         "ee-rstdoc-:leanmeta")
# (find-angg ".emacs.lean.el" "ee-rstdoc-:leanmeta")
# (to "mySpecialCheck")
# (to "mdgen")
# (find-es "minted")
# (find-lean4-intro "1. `find-wgetrecursive-links'")
# https://leanprover-community.github.io/lean4-metaprogramming-book/md/

# https://github.com/leanprover-community/
# https://github.com/leanprover-community/lean4-metaprogramming-book
# (find-git-links "https://github.com/leanprover-community/lean4-metaprogramming-book" "leanmeta")
# (code-c-d "leanmeta" "~/usrc/lean4-metaprogramming-book/")
# (find-leanmetafile "")
# (find-leanmetash "find * | sort")
# (find-leanmetash "cd lean; find * | sort")
# (find-leanmetafile "lean/main/01_intro.lean")

# (find-wgetrecursive-links "https://leanprover-community.github.io/lean4-metaprogramming-book/")
# (find-leanmetadoc)
# (find-leanmetadoc  "main/06_macros")
# (find-leanmetadoc  "main/03_expressions")

# (find-leanmetadocrfile "main/07_elaboration.lean")

# (find-leanmetadoc  "main/01_intro")
# (find-leanmetadoc  "main/01_intro#book-structure")
# (find-leanmetadoc  "main/01_intro#building-a-command")
# (find-leanmetadocr "main/01_intro#building-a-command")
# (find-leanmetadoc  "main/02_overview")
# (find-leanmetadoc  "main/03_expressions")
# (find-leanmetadoc  "main/04_metam")
# (find-leanmetadoc  "main/04_metam#full-normalisation")
# (find-leanmetadoc  "main/04_metam#constructing-expressions")
# (find-leanmetadocr "main/04_metam#constructing-expressions")
# (find-leanmetadocw "main/04_metam#constructing-expressions")
# (find-leanmetadoc  "main/04_metam#deconstructing-expressions")
# (find-leanmetadoc  "main/05_syntax")
# (find-leanmetadoc  "main/06_macros")
# (find-leanmetadoc  "main/07_elaboration")
# (find-leanmetadocr "main/07_elaboration" "### Giving meaning to commands" "MonadEnv")
# (find-leanmetadoc  "main/08_dsls")
# (find-leanmetadoc  "main/09_tactics")
# (find-leanmetadoc  "main/10_cheat-sheet")

# (find-git-links "https://github.com/leanprover-community/lean4-metaprogramming-book" "leanmeta")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv ~/usrc/lean4-metaprogramming-book/
cd      ~/usrc/
git clone https://github.com/leanprover-community/lean4-metaprogramming-book
cd      ~/usrc/lean4-metaprogramming-book/

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
cd      ~/usrc/lean4-metaprogramming-book/
git clean -dfx
git pull

lake exe cache get
lake exe cache get!

lake exe mdgen lean md
lake exe mdgen lean md

lake build lean4-metaprogramming-book |& tee olb
lake build lean4-metaprogramming-book md |& tee olb

# (code-c-d "leanmeta" "~/usrc/lean4-metaprogramming-book/")
# (find-leanmetafile "")
# (find-leanmetafile "md/")
# (find-leanmetafile "pygments/")
# (find-leanmetafile "lakefile.lean")
# (find-leanmetafile "olb")
# (find-leanmetash "find * | sort")
# (find-leanmetash "find .lake | sort")
# (find-leanmetash "find .lake * | sort")
# (find-leanmetash "find .lake * | rev | sort | rev")
# (find-leanmetafile ".lake/packages/std/")
# (find-leanmetagrep "grep --color=auto -niRH --null -e pdf * .lake")
# (find-leanmetagrep "grep --color=auto -niRH --null -e mdgen * .lake")
# (find-leanmetagrep "grep --color=auto -niRH --null -e 'lake exe' * .lake")
# (find-leanmetagrep "grep --color=auto -niRH --null -e pygments * .lake")
# (find-leanmetafile ".lake/packages/mdgen/")
# (find-leanmetafile ".lake/packages/mdgen/README.md")
# (find-leanmetafile ".lake/packages/mdgen/README.md" "lake exe mdgen <input_dir> <output_dir>")



#####
#
# metaprogramming-book.yml
# 2024may28
#
#####

# «metaprogramming-book.yml»  (to ".metaprogramming-book.yml")
# (find-leanmetafile ".github/workflows/book.yml")




#####
#
# metaprogramming-toolchain
# 2024may26
#
#####

# «metaprogramming-toolchain»  (to ".metaprogramming-toolchain")
# https://leanprover-community.github.io/install/project.html#working-on-an-existing-project

# (to "toolchains")
# (find-leanmetafile "")
# (find-leanmetafile "lake-manifest.json")
# (find-leanmetafile "lake-manifest.json" "inputRev")
# (find-leanmetafile "lake-manifest.json" "inputRev" "v4.7.0")
# (find-leanmetafile "lakefile.lean")
# (find-leanmetafile "lakefile.lean" "require std from git")
# (find-leanmetafile "lakefile.lean" "require std from git" "v4.7.0")
# (find-leanmetafile "lean-toolchain")
# (find-leanmetafile "lean-toolchain" "leanprover/lean4:v4.7.0")





#####
#
# TermElabM
# 2024may25
#
#####

# «TermElabM»  (to ".TermElabM")
# (to "mySpecialCheck")
# (find-leanmetadocr "main/07_elaboration" "`TermElabM` is basically an upgrade of")







#####
#
# Theorem Proving in Lean 4
# 2024may19
#
#####

# «tpil»  (to ".tpil")
# (find-angg ".emacs" "ee-rstdoc-:tpil4")
# (find-angg ".emacs.lean.el" "ee-rstdoc-:tpil4")
# https://lean-lang.org/theorem_proving_in_lean4/title_page.html
# https://github.com/leanprover/theorem_proving_in_lean4
# (find-wgetrecursive-links "https://lean-lang.org/theorem_proving_in_lean4/")
# (find-git-links "https://github.com/leanprover/theorem_proving_in_lean4" "tpil")
# (code-c-d "tpil" "~/usrc/theorem_proving_in_lean4/")
# (find-tpilfile "")




#####
#
# useandabuseoip
# 2024may25
#
#####

# «useandabuseoip»  (to ".useandabuseoip")
# (find-psne-arxiv-links "https://arxiv.org/pdf/2202.01629v3.pdf" "useandabuseoip")

;; <useandabuseoip>
;; https://arxiv.org/abs/2202.01629v3
;; https://arxiv.org/pdf/2202.01629v3.pdf
;; Anne Baanen: "Use and abuse of instance parameters in the Lean mathematical library"
(code-pdf-page "useandabuseoip" "$S/https/arxiv.org/pdf/2202.01629v3.pdf")
(code-pdf-text "useandabuseoip" "$S/https/arxiv.org/pdf/2202.01629v3.pdf")
;; (find-useandabuseoippage)
;; (find-useandabuseoiptext)





#####
#
# Sebastian Ullrich: Lean Together 2021 - Metaprogramming in Lean 4
# 2024mar11
#
#####

# «ullrichmp»  (to ".ullrichmp")
# (to "pratt-parser")
# (find-angg ".emacs.lean.el" "lt2021leo")
# (find-angg ".emacs.lean.el" "lt2021leom")

https://www.researchgate.net/scientific-contributions/Sebastian-Ullrich-2132232638
https://leanprover-community.github.io/papers.html
https://leanprover-community.github.io/lt2021/
https://leanprover-community.github.io/lt2021/schedule.html ***
https://leanprover-community.github.io/lt2021/slides/leo-LT2021.pdf
https://leanprover-community.github.io/lt2021/slides/leo-LT2021-meta.pdf
https://leanprover-community.github.io/lt2021/slides/sebastian-lean4-parsers-macros.pdf
https://leanprover-community.github.io/lt2021/slides/sebastian-An-Overview-of-Lean-4-Demo.pdf
https://leanprover-community.github.io/lt2021/slides/gihan-exlean_2021.pdf
https://leanprover-community.github.io/lt2021/slides/thomas-LT2021-Galois-Theory.pdf

# (find-youtubedl-links "/sda5/videos/" "Lean_Together_2021_-_Metaprogramming_in_Lean_4" "hxQ1vvhYN_U" ".webm" "lt2021sebastianleo")


# (code-video "ullrichmpvideo" "/sda5/videos/Lean_Together_2021_-_Metaprogramming_in_Lean_4-hxQ1vvhYN_U.webm")
# (find-ullrichmpvideo "0:00")
# (find-ullrichmpvideo "6:50" "notation")
# (find-ullrichmpvideo "8:45" "trace.Elab.command")
# (find-ullrichmpvideo "9:30" "for the next command")
# (find-ullrichmpvideo "12:00" "longest parse wins")
# (find-ullrichmpvideo "26:45" "crosses")

(code-pdf-page "ullrichmp" "$S/https/leanprover-community.github.io/lt2021/slides/sebastian-lean4-parsers-macros.pdf")
(code-pdf-text "ullrichmp" "$S/https/leanprover-community.github.io/lt2021/slides/sebastian-lean4-parsers-macros.pdf")
;; (find-ullrichmppage)
;; (find-ullrichmptext)
# (find-ullrichmppage 13 "precedence (Pratt) parser")
# (find-ullrichmptext 13 "precedence (Pratt) parser")

# (find-leanmetadoc "md/main/05_syntax#declaration-helpers" "longest parse")



#####
#
# mechanics-of-proof
# 2024jun01
#
#####

# «mechanics-of-proof»  (to ".mechanics-of-proof")
# «:mechprf»                       (to ".:mechprf")
# (find-angg ".emacs.lean.el" "ee-rstdoc-:mechprf")
# https://hrmacbeth.github.io/math2001/
# (find-git-links "https://github.com/hrmacbeth/math2001" "mechprf")
# (code-c-d "mechprf" "~/usrc/math2001/")
# (find-mechprffile "")
# (find-mechprffile "README.md")
# (find-mechprffile "Library/")
# (find-mechprffile "Math2001/")

# (find-mechprfdoc      "01_Proofs_by_Calculation")
# (find-mechprfdocw     "01_Proofs_by_Calculation")
# (find-mechprfdocrfile "01_Proofs_by_Calculation/")




#####
#
# Colorized
# 2024jun04
#
#####

# «Colorized»  (to ".Colorized")
# (to "lake-current-directory")
# (find-telegachat  "@leanlangbr#520" "lakefile current directory")
# https://github.com/axiomed
# https://github.com/axiomed/Colorized.lean
# https://github.com/algebraic-sofia?tab=repositories
# https://github.com/edrx
# (find-git-links "https://github.com/axiomed/Colorized.lean" "colorized")
# (code-c-d "colorized" "~/usrc/Colorized.lean/")
# (find-colorizedfile "")

* (eepitch-shell)
* (eepitch-kill)
* (eepitch-shell)
rm -Rfv ~/usrc/Colorized.lean/
cd      ~/usrc/
git clone https://github.com/axiomed/Colorized.lean
cd      ~/usrc/Colorized.lean/
# lake exe example
# lake exe example

# (find-colorizedfile "")
# (find-colorizedfile "lakefile.lean")
# (find-colorizedfile "Example.lean")
# (find-colorizedfile "Colorized.lean")





#####
#
# leandojo
# 2024jun07
#
#####

# «leandojo»  (to ".leandojo")
# https://leandojo.readthedocs.io/en/latest/user-guide.html#traced-repos




#####
#
# `do' Unchained: Embracing Local Imperativity in a Purely Functional Language
# 2024jun14
#
#####

# «do-unchained»  (to ".do-unchained")
# (to "let-mut")

;; https://lean-lang.org/papers/do.pdf
;; `do' Unchained: Embracing Local Imperativity in a Purely Functional Language (Functional Pearl)
;; SEBASTIAN ULLRICH, Karlsruhe Institute of Technology, Germany
;; LEONARDO DE MOURA, Microsoft Research, USA
;; (find-fline "$S/https/lean-lang.org/papers/")
(code-pdf-page  "dounchained" "$S/https/lean-lang.org/papers/do.pdf")
(code-pdf-text8 "dounchained" "$S/https/lean-lang.org/papers/do.pdf")
;; (find-dounchainedpage)
;; (find-dounchainedtext)





















stdout.putStrLn


# (find-fplean4page 76 "import «Greeting»")
# (find-fplean4text 76 "import «Greeting»")



https://leanprover-community.github.io/lean4-metaprogramming-book/md/main/01_intro.html#introducing-notation-defining-new-syntax





https://lovettsoftware.com/NaturalNumbers/PropositionWorld.lean.html

Proposition world.

A Proposition is a true/false statement, like 2 + 2 = 4 or 2 + 2 = 5.
Just like we can have concrete sets in Lean like mynat, and abstract
sets called things like X, we can also have concrete propositions like
2 + 2 = 5 and abstract propositions called things like P.

Mathematicians are very good at conflating a theorem with its proof.
They might say "now use theorem 12 and we're done". What they really
mean is "now use the proof of theorem 12..." (i.e. the fact that we
proved it already). Particularly problematic is the fact that
mathematicians use the word Proposition to mean "a relatively
straightforward statement which is true" and computer scientists use
it to mean "a statement of arbitrary complexity, which might be true
or false". Computer scientists are far more careful about
distinguishing between a proposition and a proof. For example: x + 0 =
x is a proposition, and add_zero x is its proof. The convention we'll
use is capital letters for propositions and small letters for proofs.


https://www.ma.imperial.ac.uk/~buzzard/xena/natural_number_game/FAQ.html
https://github.com/ImperialCollegeLondon/natural_number_game
https://github.com/mpedramfar/Lean-game-maker






https://xenaproject.wordpress.com/2021/06/05/half-a-year-of-the-liquid-tensor-experiment-amazing-developments/
Picking a basis and then pretending you didn’t

https://github.com/leanprover-community/leanprover-community.github.io/blob/newsite/data/zulip.md

https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Calling.20lean.20from.20command.20line


https://www.ma.imperial.ac.uk/~buzzard/xena/natural_number_game/
https://www.microsoft.com/en-us/research/uploads/prod/2020/11/perceus-tr-v1.pdf

(find-books "__comp/__comp.el" "colton")

https://leanprover.github.io/reference/
https://leanprover.github.io/reference/using_lean.html#using-lean-with-emacs
https://lawrencecpaulson.github.io/2023/01/18/Sqrt2_irrational.html
https://news.ycombinator.com/item?id=34437735 Formalising a new proof that the square root of two is irrational (lawrencecpaulson.github.io) ***
https://news.ycombinator.com/item?id=35511152 What I've Learned About Formal Methods in Half a Year (jakob.space)

;; <schemesinlean>
;; https://arxiv.org/abs/2101.02602
;; https://arxiv.org/pdf/2101.02602.pdf
(code-pdf-page "schemesinlean" "$S/https/arxiv.org/pdf/2101.02602.pdf")
(code-pdf-text "schemesinlean" "$S/https/arxiv.org/pdf/2101.02602.pdf")
;; (find-schemesinleanpage)
;; (find-schemesinleantext)

https://proofassistants.stackexchange.com/questions/2153/type-theory-lean-3-to-lean-4

;; <ullrichmhm>
;; https://arxiv.org/abs/2001.10490
;; https://arxiv.org/pdf/2001.10490.pdf
;; Ullrich/Moura: "Beyond Notations: Hygienic Macro Expansion for Theorem Proving Languages"
(code-pdf-page "ullrichmhm" "$S/https/arxiv.org/pdf/2001.10490.pdf")
(code-pdf-text "ullrichmhm" "$S/https/arxiv.org/pdf/2001.10490.pdf")
;; (find-ullrichmhmpage)
;; (find-ullrichmhmtext)
# (find-ullrichmhmpage 13 "token antiquotation %$x")
# (find-ullrichmhmtext 13 "token antiquotation %$x")

;; <leanteach2020>
;; https://github.com/vaibhavkarve/leanteach2020
;; https://vaibhavkarve.github.io/leanteach_report.pdf
;; https://wiki.illinois.edu/wiki/display/LT2020/LeanTeach+2020+Home
;; Dolcos/Kong/Zhao/Phillips/Karve: "Interactive Theorem Proving in Lean"
(code-pdf-page "leanteach2020" "$S/https/vaibhavkarve.github.io/leanteach_report.pdf")
(code-pdf-text "leanteach2020" "$S/https/vaibhavkarve.github.io/leanteach_report.pdf")
(code-c-d      "leanteach2020"      "~/usrc/leanteach2020/")
(code-video    "leanteach2020video" "~/usrc/leanteach2020/igl_talk.mp4")
;; (find-leanteach2020page)
;; (find-leanteach2020text)

# (find-git-links "https://github.com/vaibhavkarve/leanteach2020" "leanteach2020")
# (find-leanteach2020file "")
# (find-leanteach2020video)
# (find-leanteach2020video "0:00")

https://pp.ipd.kit.edu/person.php?id=144 Dr.-Ing. Sebastian Ullrich
https://www.math.uni-bonn.de/ag/logik/events/MLPTT/Ullrich_lean.pdf Embedding Languages into Lean 4

;; <ullrichemb>
;; https://www.math.uni-bonn.de/ag/logik/events/MLPTT/Ullrich_lean.pdf
;; (find-fline "$S/https/www.math.uni-bonn.de/ag/logik/events/MLPTT/")
(code-pdf-page "ullrichemb" "$S/https/www.math.uni-bonn.de/ag/logik/events/MLPTT/Ullrich_lean.pdf")
(code-pdf-text "ullrichemb" "$S/https/www.math.uni-bonn.de/ag/logik/events/MLPTT/Ullrich_lean.pdf")
;; (find-ullrichembpage)
;; (find-ullrichembtext)
# (find-ullrichembpage 20 "ParserContext =")
# (find-ullrichembtext 20 "ParserContext =")

https://leanprover.github.io/presentations/20181012_MSR/#/4
https://leanprover-community.github.io/lt2021/slides/sebastian-An-Overview-of-Lean-4-Demo.pdf




https://jiggerwit.wordpress.com/2018/09/18/a-review-of-the-lean-theorem-prover/ elaborator
https://jiggerwit.wordpress.com/2019/06/20/an-argument-for-controlled-natural-languages-in-mathematics/

https://leanprover.github.io/papers/lean4.pdf



https://leanprover-community.github.io/archive/stream/270676-lean4/topic/Metaprogramming.20tutorial.html

https://github.com/leanprover-community/quote4

https://leanprover-community.github.io/undergrad.html
https://leanprover-community.github.io/mathlib4_docs/Mathlib/Analysis/NormedSpace/Exponential.html#NormedSpace.exp
https://leanprover-community.github.io/mathlib-overview.html
https://leanprover-community.github.io/mathlib4_docs/Mathlib/CategoryTheory/Yoneda.html#CategoryTheory.yoneda
https://leanprover-community.github.io/theories/category_theory.html
https://github.com/ImperialCollegeLondon/formalising-mathematics-2024
https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Project.20idea.3A.20linking.20MathLib.20to.20math.20books
https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/idiom.20for.20using.20calc.20to.20rewrite.20the.20goal

https://github.com/leanprover-community/lean4-samples/blob/main/RubiksCube/README.md
https://lean-lang.org/lean4/doc/examples/widgets.lean.html
https://github.com/leanprover-community/lean4-samples/blob/main/ListComprehension/README.md
https://github.com/leanprover-community/lean4-samples/blob/main/GuessMyNumber/README.md

https://florisvandoorn.com/ HOTT in Lean

(find-lean4prefile "Init/Prelude.lean" "triangle")

https://github.com/kmill
https://github.com/kmill/lean4-raytracer
https://github.com/kmill/LeanTeX
https://github.com/kmill/glimpse_of_lean
https://github.com/kmill/leanprover-community.github.io
https://github.com/kmill/tutorials
https://leanprover-community.github.io/archive/stream/270676-lean4/topic/getting.20started.20with.20Lean.204.html
https://kmill.github.io/cv/cv.pdf

https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Creating.20Expr.20objects/near/438922814




@_**Eduardo Ochs|381195** [said](https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/leading_parser.3F/near/439313997):
````quote
Now about the output of "`#print foo`": wow and thanks! It works here, but I think that I need to understand other things before understanding that... and my guess is that would be a good idea to start by understand how "`deriving Repr`" works in a simple case. I tried this,

```
inductive myNat where
  | zero             : myNat
  | succ (n : myNat) : myNat
  deriving Repr

def my1 := myNat.succ myNat.zero
#check my1
#eval  my1
#print my1
#check repr my1
#eval  repr my1
#print repr my1
#check Std.Format
```

and then:

1) the method "`repr`" for the type `myNat` is not in a super-obvious place, like in `myNat.repr`,

2) the output of "`#check repr my1`" is "`repr my1 : Std.Format`", and I don't have test snippets (yet) for the class [Std.Format](https://github.com/leanprover/lean4/blob/master/src/Init/Data/Format/Basic.lean),

3) but I read some parts of the source starting by "[mkReprInstanceHandler](https://github.com/leanprover/lean4/blob/master/src/Lean/Elab/Deriving/Repr.lean#L118)" and I found references to "[isInductive](https://github.com/leanprover/lean4/blob/master/src/Lean/MonadEnv.lean#L27)" and "[getStructureFields](https://github.com/leanprover/lean4/blob/master/src/Lean/Structure.lean#L79)" - they look very useful, can we start by them? If yes, question: how do I call "`isInductive`" and "`getStructureFields`" on the "`myNat`" or on the "`my1`" of the example above?

Thanks in advance!
````




https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/leading_parser.3F/near/439313997



How to use getStructureFields
Hi all! How can I use [getStructureFields](https://github.com/leanprover/lean4/blob/master/src/Lean/Structure.lean#L79) to obtain the fields of a structure? Or, to be more concrete, how can I use it to obtain the fields of myNat after running this?

```
inductive myNat where
  | zero             : myNat
  | succ (n : myNat) : myNat
  deriving Repr

def my1 := myNat.succ myNat.zero
#check my1
#eval  my1
#print my1
```

NOTE: the question above is similar to one that I asked in a [thread about leading_parser](https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/leading_parser.3F), and it may be related to [this thread](https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/How.20do.20I.20write.20a.20.22.23check_syntax.22.3F/near/438953824), in which 

showed me this example of how to write a command...

```
import Lean.Elab.Command
elab "#check_syntax " t:term : command => do Lean.logInfo m!"{repr t.raw}"
#check_syntax 42 + "foo"
```

https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/Proving.20extentionality.20for.20category.20structure.20with.207.20entries
https://www.ma.imperial.ac.uk/~buzzard/xena/pdfs/BuzzardICM2022talk.pdf
https://gilkalai.wordpress.com/2022/07/17/icm-2022-kevin-buzzard-the-rise-of-formalism-in-mathematics/
https://alectryon-paper.github.io/bench/books/proof-by-reflection.html

# Clément Pit-Claudel: "Untangling mechanized proofs"
# https://dl.acm.org/doi/10.1145/3426425.3426940 
# https://dl.acm.org/doi/pdf/10.1145/3426425.3426940

https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/writing.20simple.20parsers Parsec
https://news.ycombinator.com/item?id=34456573 Lean – Theorem Prover (leanprover.github.io)

;; <ochigame>
;; https://arxiv.org/abs/2309.11457v1
;; https://arxiv.org/abs/2309.11457v1.pdf
(code-pdf-page "ochigame" "$S/https/arxiv.org/abs/2309.11457v1.pdf")
(code-pdf-text "ochigame" "$S/https/arxiv.org/abs/2309.11457v1.pdf")
;; (find-ochigamepage)
;; (find-ochigametext)

https://mathstodon.xyz/@tao/111208692505811257 Terence Tao and the NNG
https://fredrikj.net/blog/2022/04/things-i-would-like-to-see-in-a-computer-algebra-system/#section7

Lean phrasebook:
https://docs.google.com/spreadsheets/d/1Gsn5al4hlpNc_xKoXdU6XGmMyLiX4q-LFesFVsMlANo/edit#gid=854838157

https://media.ccc.de/v/gpn22-483-intro-to-lean-4-a-language-at-the-intersection-of-programming-and-mathematics
https://lean-fro.org/about/roadmap/

https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/.E2.9C.94.20Lean4.20equivalent.20of.20library_search.20and.20suggest
https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/.E2.9C.94.20Discussion.3A.20Making.20Your.20Lean.20Code.20More.20Readable focusing dot

# Kyle Miller, 2024jun12 - Here's the sort of mental model I have for Lean's type system:
# https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/.E2.9C.94.20Type.20and.20Type*/near/444063991

https://github.com/PatrickMassot/GlimpseOfLean

Proof Visualization for the Lean 4 theorem prover
https://pp.ipd.kit.edu/uploads/publikationen/b%C3%BClow22bachelorarbeit.pdf 






#  Local Variables:
#  coding:           utf-8-unix
#  End: