Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CSwL/Logic/PL.lean
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ example : Maria.form₁.names₁ == ["MB", "MJ", "MT"] :=
:::


Nem todos os conectivos precisam ser definidos como "primitivos". Como vimos na seção {ref "pl-lean"}[pl-lean] a implicação pode ser definida como uma disjunção. E a dupla implicação como uma conjunção de implicações.
Nem todos os conectivos precisam ser definidos como "primitivos". Como vimos no exercício {cref "implication-as-disj"}[], a implicação pode ser definida como uma disjunção. E a dupla implicação como uma conjunção de implicações.

```lean
def Formula.impl (f g : Formula) : Formula := .disj (.neg f) g
Expand Down Expand Up @@ -380,7 +380,7 @@ def Formula.contradiction (f : Formula) : Bool :=
#eval form1.satisfiable
```

E como já sabemos da seção {ref "pl-lean"}[pl-lean], podemos mostrar que {name}`form3` é uma tautologia.
E como já sabemos do exercício {cref "implication-as-disj"}[], podemos mostrar que {name}`form3` é uma tautologia.

```lean
#eval form3.tautology
Expand Down
2 changes: 1 addition & 1 deletion CSwL/Logic/Proof.lean
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ tag := "counterexamples"

Considere o argumento: "se chover, a rua fica molhada. A rua está molhada. Logo, choveu."

Com `p` para "chove" e `q` para "a rua fica molhada", podemos formalizá-lo como fizemos no exercício `prop-exchange`.
Com `p` para "chove" e `q` para "a rua fica molhada", podemos formalizá-lo como fizemos no exercício {cref "prop-exchange"}[].

```lean
namespace WetStreet
Expand Down
1 change: 1 addition & 0 deletions CSwLMeta.lean
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import CSwLMeta.Save
import CSwLMeta.Solution
import CSwLMeta.Terse
import CSwLMeta.Variant
import CSwLMeta.Cref

namespace CSwLMeta

Expand Down
96 changes: 96 additions & 0 deletions CSwLMeta/Cref.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import VersoManual
import CSwLMeta.Exercise

/-!
# Cross-references to sections and exercises

`{cref "tag"}[text]` links to the section whose `tag` is `"tag"` or to the
exercise whose `name` is `"tag"`. With empty brackets, `{cref "tag"}[]`, the
link text is generated: the section's title, or the exercise's name in code.
The text therefore follows the title when the title changes. Nothing else is
added: the prose names the kind of target, as in "no exercício {cref …}[]".

The text is generated during traversal, by replacing the node with one that
carries the text as its content. The HTML and the extracted Lean projects
(`CSwLMeta/Save`), which render an inline's content, both see it.

A tag that names neither a section nor an exercise, or that names both, is
reported as an error.
-/

open Lean Elab
open Verso ArgParse Doc Elab Genre.Manual
open Verso.Output Verso.Output.Html

namespace CSwLMeta

/-- The target of a cross-reference: where it links and the text to show
when the reference brings none. -/
structure CrefTarget where
/-- The URL of the target. -/
href : String
text : Array (Verso.Doc.Inline Manual)

/-- Resolve `name` among the section tags and the exercise names. -/
def resolveCref (st : TraverseState) (name : String) :
Except String CrefTarget := do
let sec? := st.getDomainObject? sectionDomain name
let ex? := st.getDomainObject? exerciseDomain name
match sec?, ex? with
| some _, some _ =>
throw s!"'{name}' is both a section tag and an exercise name"
| some obj, none =>
let title := (obj.data.getObjValAs? String "title").toOption.getD name
match st.resolveDomainObject sectionDomain name with
| .error e => throw e
| .ok dest => return { href := dest.link, text := #[.text title] }
| none, some _ =>
match st.resolveDomainObject exerciseDomain name with
| .error e => throw e
| .ok dest =>
return { href := dest.link, text := #[.code name] }
| none, none =>
throw s!"No section tag or exercise name '{name}'"

-- A cross-reference to the section or exercise `name`.
inline_extension Inline.cref (name : String) where
data := toJson name
-- With empty content, fill in the generated text once the target is known.
-- An unknown target is left alone here: a later pass may register it, and
-- `toHtml` reports it if none does.
traverse _ data content := do
let .ok (name : String) := fromJson? data | pure none
unless content.isEmpty do return none
match resolveCref (← get) name with
| .ok tgt => return some (.other (Inline.cref name) tgt.text)
| .error _ => return none
toHtml :=
some fun go _ data content => do
let .ok (name : String) := fromJson? data
| reportError s!"Bad cref data {data}"; content.mapM go
match resolveCref (← Doc.Html.HtmlT.state) name with
| .ok tgt =>
let body ← (if content.isEmpty then tgt.text else content).mapM go
return {{<a href={{tgt.href}}>{{body}}</a>}}
| .error e =>
reportError e
content.mapM go
toTeX :=
some fun go _ _ content => content.mapM go

structure CrefArgs where
name : String

instance [Monad m] [MonadError m] : FromArgs CrefArgs m where
fromArgs := CrefArgs.mk <$> .positional `name .string

/-- `{cref "tag"}[text]` links to a section or exercise; `{cref "tag"}[]`
generates the text. -/
@[role]
def cref : RoleExpanderOf CrefArgs
| {name}, content => do
let content ← content.mapM elabInline
``(Verso.Doc.Inline.other (CSwLMeta.Inline.cref $(quote name))
#[$content,*])

end CSwLMeta
23 changes: 19 additions & 4 deletions CSwLMeta/Exercise.lean
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
-- Adapted from sf-in-lean/SFLMeta/Exercise.lean
-- (namespace SFLMeta -> CSwLMeta and nothing else: the
-- (namespace SFLMeta -> CSwLMeta; besides, `Block.exercise` gets an HTML
-- anchor and registers its name in `exerciseDomain`, for `{cref}`. The
-- `solution!`/`workinclass!`/`suggested!` elaborators and the edit registry
-- are a literal copy -- this is the delicate part, validated against this
-- revision of Verso).
Expand Down Expand Up @@ -71,13 +72,26 @@ def decodeExerciseData (data : Json) : Nat × String × Option String × Bool :=
| .arr #[.num jr, .str n] => (jr.toFloat.toUInt32.toNat, n, none, false)
| _ => (0, "", none, false)

/-- The domain in which every exercise registers its `name`, so that `{cref}`
can link to it. -/
def exerciseDomain : Name := `CSwLMeta.exercise

block_extension Block.exercise (rating : Nat) (name : String)
(level : Option String) (manual : Bool) where
data := Json.arr #[.num (.fromNat rating), .str name, toJson level, .bool manual]
traverse _ _ _ := pure none
-- Give the exercise an anchor and register its name in `exerciseDomain`.
-- All three steps are idempotent, so repeated traversal passes are harmless.
traverse id data _ := do
let (_, name, _, _) := decodeExerciseData data
let path ← (·.path) <$> read
let _ ← Verso.Genre.Manual.externalTag id path s!"ex-{name}"
modify fun st => st
|>.saveDomainObject exerciseDomain name id
|>.saveDomainObjectData exerciseDomain name (json%{"name": $name})
pure none
toHtml :=
open Verso.Output.Html in
some fun _ goB _ data contents => do
some fun _ goB id data contents => do
let (rating, name, level, manual) := decodeExerciseData data
let stars := String.ofList (List.replicate rating '★')
let desig := exerciseDesignation level manual
Expand All @@ -86,8 +100,9 @@ block_extension Block.exercise (rating : Nat) (name : String)
else {{ <span class="exercise-level">{{desig}}</span> }}
let body : Verso.Output.Html ← contents.foldlM (init := .empty) fun acc b =>
return acc ++ (← goB b)
let idAttr := (← Verso.Doc.Html.HtmlT.state).htmlId id
return {{
<div class={{s!"exercise stars-{rating}"}}>
<div class={{s!"exercise stars-{rating}"}} {{idAttr}}>
<div class="exercise-header">
<span class="exercise-label">"Exercício"</span>
<span class="exercise-stars">{{stars}}</span>
Expand Down
15 changes: 15 additions & 0 deletions STYLE-CODE.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,21 @@ each gets its cues when it is next revised.
- `{include N Module}` — pulls a section file into its glue chapter at heading
depth `N`.

### Cross-references

- `{cref "tag"}[]` — links to the section whose `tag :=` is `"tag"`, or to
the exercise whose `name :=` is `"tag"`, and generates the link text: the
section's title, or the exercise's name in code. Nothing else is added;
the prose names the kind of target ("no exercício {cref …}[]").
Defined in `CSwLMeta/Cref.lean`. The text is filled in during traversal,
so the HTML and the generated Lean projects both carry it.
- `{cref "tag"}[texto]` — the same link with the text written by hand.
- A tag that names neither a section nor an exercise, or both, fails the
build. Exercise names must therefore be unique across the book, and must
not coincide with a section tag.
- Verso's `{ref "tag"}[texto]` still works for sections, but its text is
always hand-written and can drift from the title.

## Lean style

Follow the Mathlib
Expand Down
9 changes: 9 additions & 0 deletions STYLE-WRITING.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ moves between chapters — that is why nothing in this book is numbered. A
`{ref "Tag"}[…]` survives a reorder; "the previous chapter" silently becomes
false.

**Prefer `{cref "tag"}[]` for cross-references.** It links to a section or
an exercise and takes its text from the target: the section's title, or the
exercise's name in code. It adds nothing else, so the prose says what is
being cited: "seção", "capítulo", "exercício". The text then follows the title when the title changes,
so it cannot fall out of step with it. Write the surrounding words so that
the generated text fits: "como fizemos no exercício {cref "prop-exchange"}[]",
"visto no capítulo {cref "IntroCS"}[]". Write the text by hand,
`{cref "tag"}[texto]`, only when the sentence needs other words.

Where a positional phrase is genuinely the clearest thing to write, it is a
liability to be repaid: **after moving any chapter or section, sweep for the
prose the move invalidated.** The search that has caught them so far:
Expand Down