Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
472 lines (446 loc) · 12.9 KB
/
Copy pathmain.go
File metadata and controls
472 lines (446 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// Code generated by litgo from litgo.lit.md; DO NOT EDIT.
package main
import (
"encoding/json"
"flag"
"fmt"
"go/format"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/tlehman/litgo/internal/check"
"github.com/tlehman/litgo/internal/lit"
"github.com/tlehman/litgo/internal/lsp"
"github.com/tlehman/litgo/internal/vego"
"github.com/tlehman/litgo/internal/weave"
)
const usage = `litgo — literate Go
litgo tangle [--force] [--stdout] FILE.lit.md... write the Go source
litgo run [--vet] [--no-prove] [--timeout 30s] FILE [-- ARGS]
tangle, prove, compile and run
litgo weave [--to pdf|html|typ|md] [-o OUT] FILE write a PDF through Typst, or a web page
litgo check FILE.lit.md... chunk, syntax, type and proof errors; writes nothing
litgo prove [--json] FILE.lit.md... check the //@ annotations: contracts, invariants, termination
litgo cat FILE.lit.md print with math and diagrams rendered
litgo fmt [-w] FILE.lit.md gofmt the code blocks
Editor protocol (document on stdin, JSON on stdout):
litgo analyze [--path P] [--upright]
litgo untangle --start L --end L [--start-col C --end-col C] [--name N]
litgo rename --from NAME --to NAME
litgo run --json FILE one JSON event per line
litgo lsp [--gopls PATH|off] language server on stdin/stdout: errors as you type,
and gopls for the Go in the code blocks
Positions in the editor protocol are 0-based; columns are bytes.
`
const VERSION = "0.2.3"
func main() {
if len(os.Args) < 2 {
fmt.Fprint(os.Stderr, usage)
os.Exit(2)
}
cmd, args := os.Args[1], os.Args[2:]
switch cmd {
case "tangle":
os.Exit(cmdTangle(args))
case "run":
os.Exit(cmdRun(args))
case "weave":
os.Exit(cmdWeave(args))
case "check":
os.Exit(cmdCheck(args))
case "prove":
os.Exit(cmdProve(args))
case "cat":
os.Exit(cmdCat(args))
case "fmt":
os.Exit(cmdFmt(args))
case "analyze":
os.Exit(cmdAnalyze(args))
case "untangle":
os.Exit(cmdUntangle(args))
case "version":
os.Exit(cmdVersion(args))
case "rename":
os.Exit(cmdRename(args))
case "lsp":
fs := flag.NewFlagSet("lsp", flag.ExitOnError)
gopls := fs.String("gopls", "", "the gopls to put behind the server; found when empty, none when \"off\"")
fs.Parse(args)
if err := lsp.Serve(os.Stdin, os.Stdout, *gopls); err != nil {
fmt.Fprintln(os.Stderr, "litgo lsp:", err)
os.Exit(1)
}
case "help", "-h", "--help":
fmt.Print(usage)
default:
fmt.Fprintf(os.Stderr, "litgo: unknown command %q\n\n%s", cmd, usage)
os.Exit(2)
}
}
func load(path string) (*lit.Doc, error) {
abs, err := filepath.Abs(path)
if err != nil {
return nil, err
}
src, err := os.ReadFile(abs)
if err != nil {
return nil, err
}
return lit.Parse(abs, src), nil
}
func stdinDoc(path string) *lit.Doc {
src, _ := io.ReadAll(os.Stdin)
if path == "" {
path = "stdin.lit.md"
}
return lit.Parse(path, src)
}
func printJSON(v any) int {
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
return 1
}
return 0
}
func jsonError(err error) int {
printJSON(map[string]string{"error": err.Error()})
return 1
}
func report(diags []lit.Diag) (errors int) {
r := &reporter{seen: map[string]bool{}}
for _, d := range diags {
r.diag(d)
if d.Severity == lit.SevError {
errors++
}
}
return errors
}
func cmdTangle(args []string) int {
fs := flag.NewFlagSet("tangle", flag.ExitOnError)
force := fs.Bool("force", false, "overwrite files litgo did not generate")
stdout := fs.Bool("stdout", false, "print instead of writing")
fs.Parse(args)
if fs.NArg() == 0 {
fmt.Fprintln(os.Stderr, "litgo tangle: no input files")
return 2
}
status := 0
for _, path := range fs.Args() {
doc, err := load(path)
if err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
status = 1
continue
}
res := doc.Tangle()
if report(res.Diags) > 0 {
status = 1
continue
}
for _, o := range res.Files {
if *stdout {
if len(res.Files) > 1 {
fmt.Printf("==> %s <==\n", relPath(o.Path))
}
os.Stdout.Write(o.Bytes())
continue
}
if err := writeTangled(o, *force); err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
status = 1
continue
}
fmt.Fprintf(os.Stderr, "litgo: %s → %s (%d lines)\n", relPath(doc.Path), relPath(o.Path), len(o.Lines))
}
}
return status
}
func cmdRun(args []string) int {
fs := flag.NewFlagSet("run", flag.ExitOnError)
o := runOptions{}
fs.BoolVar(&o.json, "json", false, "emit one JSON event per line")
fs.BoolVar(&o.force, "force", false, "overwrite files litgo did not generate")
fs.BoolVar(&o.vet, "vet", false, "also run go vet")
fs.BoolVar(&o.noProve, "no-prove", false, "run even if the //@ annotations are not proved")
fs.DurationVar(&o.timeout, "timeout", 0, "kill the program after this long")
fs.Parse(args)
if fs.NArg() == 0 {
fmt.Fprintln(os.Stderr, "litgo run: no input file")
return 2
}
o.args = fs.Args()[1:]
if len(o.args) > 0 && o.args[0] == "--" {
o.args = o.args[1:]
}
return runFile(fs.Arg(0), o)
}
func cmdWeave(args []string) int {
fs := flag.NewFlagSet("weave", flag.ExitOnError)
to := fs.String("to", "", "pdf, html, typ (Typst source) or md (woven Markdown); default pdf, or what -o ends in")
out := fs.String("o", "", "output file")
fs.Parse(args)
if fs.NArg() != 1 {
fmt.Fprintln(os.Stderr, "litgo weave: expected one input file")
return 2
}
doc, err := load(fs.Arg(0))
if err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
return 1
}
format := *to
if format == "" {
format = strings.TrimPrefix(filepath.Ext(*out), ".")
}
if format == "" {
format = "pdf"
}
if *out == "" {
ext := map[string]string{"md": "woven.md"}[format]
if ext == "" {
ext = format
}
*out = strings.TrimSuffix(strings.TrimSuffix(doc.Path, ".md"), ".lit") + "." + ext
}
switch format {
case "pdf":
err = weave.PDF(doc, *out)
case "html":
err = weave.HTML(doc, *out)
case "typ":
var src string
if src, err = weave.Typst(doc); err == nil {
err = os.WriteFile(*out, []byte(src), 0o644)
}
case "md":
err = os.WriteFile(*out, []byte(weave.Markdown(doc)), 0o644)
default:
err = fmt.Errorf("cannot weave to %q: pdf, html, typ and md are what there is", format)
}
if err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
return 1
}
abs, _ := filepath.Abs(*out)
fmt.Println(abs)
return 0
}
func cmdCheck(args []string) int {
status, cache := 0, &check.Cache{}
for _, path := range args {
doc, err := load(path)
if err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
status = 1
continue
}
res := doc.Tangle()
diags := append(res.Diags, res.SyntaxCheck()...)
if len(diags) == len(res.Diags) {
diags = append(diags, check.Types(res, cache)...)
}
if len(diags) == len(res.Diags) {
proofs, _ := vego.Prove(res)
diags = append(diags, proofs...)
}
if report(diags) > 0 {
status = 1
}
}
return status
}
func cmdProve(args []string) int {
fs := flag.NewFlagSet("prove", flag.ExitOnError)
asJSON := fs.Bool("json", false, "print the findings and the count as JSON")
fs.Parse(args)
if fs.NArg() == 0 {
fmt.Fprintln(os.Stderr, "litgo prove: no input files")
return 2
}
status := 0
for _, path := range fs.Args() {
doc, err := load(path)
if err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
status = 1
continue
}
res := doc.Tangle()
diags := append(res.Diags, res.SyntaxCheck()...)
var sum vego.Summary
if len(diags) == len(res.Diags) && !res.HasErrors() {
var proofs []lit.Diag
proofs, sum = vego.Prove(res)
diags = append(diags, proofs...)
}
failed := false
for _, d := range diags {
failed = failed || d.Severity == lit.SevError
}
if failed {
status = 1
}
if *asJSON {
if diags == nil {
diags = []lit.Diag{}
}
printJSON(map[string]any{"file": doc.Path, "diagnostics": diags, "functions": sum.Functions,
"proved": sum.Proved, "obligations": sum.Obligations, "names": sum.Names})
continue
}
report(diags)
switch {
case failed && sum.Functions == 0:
case sum.Functions == 0:
fmt.Fprintf(os.Stderr, "litgo: %s has no //@ annotations, so there is nothing to prove\n", relPath(doc.Path))
default:
fmt.Fprintf(os.Stderr, "litgo: %s: proved %d of %d annotated functions (%d obligations)\n",
relPath(doc.Path), sum.Proved, sum.Functions, sum.Obligations)
for _, name := range sum.Names {
fmt.Fprintf(os.Stderr, " ✓ %s\n", name)
}
}
}
return status
}
// cmdCat prints the document the way the editor shows it: math as Unicode,
// diagrams drawn, chunk syntax prettified.
func cmdCat(args []string) int {
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "litgo cat: expected one input file")
return 2
}
doc, err := load(args[0])
if err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
return 1
}
a := doc.Analyze(lit.AnalyzeOptions{})
blocks := map[int]lit.Item{}
inline := map[int][]lit.Item{}
for _, it := range a.Items {
if it.Kind == "table" || it.Kind == "vego" {
continue // lining up a table and colouring an annotation are the editor's business
} else if len(it.Lines) > 0 {
blocks[it.Line] = it
} else {
inline[it.Line] = append(inline[it.Line], it)
}
}
for i := 0; i < len(doc.Lines); i++ {
if it, ok := blocks[i]; ok {
for _, l := range it.Lines {
fmt.Println(" " + l)
}
i = it.EndLine
continue
}
line := doc.Lines[i]
items := inline[i]
sort.Slice(items, func(a, b int) bool { return items[a].Col < items[b].Col })
for k := len(items) - 1; k >= 0; k-- { // right to left keeps columns valid
it := items[k]
line = line[:it.Col] + it.Text + line[min(it.EndCol, len(line)):]
}
fmt.Println(line)
}
return 0
}
func cmdFmt(args []string) int {
fs := flag.NewFlagSet("fmt", flag.ExitOnError)
write := fs.Bool("w", false, "write the result back instead of printing it")
fs.Parse(args)
if fs.NArg() != 1 {
fmt.Fprintln(os.Stderr, "litgo fmt: expected one input file")
return 2
}
doc, err := load(fs.Arg(0))
if err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
return 1
}
lines := append([]string{}, doc.Lines...)
for i := len(doc.Blocks) - 1; i >= 0; i-- {
b := doc.Blocks[i]
if !b.Tangled() || b.Lang != "go" || b.Last() < b.First() || b.Strip > 0 {
continue
}
// format.Source accepts fragments; blocks that only make sense once
// their chunks are spliced in fail to parse and are left alone. So are
// blocks with inline references: gofmt would tidy away the comma that
// precedes a reference standing for the rest of an argument list.
if !b.Verbatim && inlineRefs(doc.Lines[b.First():b.Last()+1]) {
continue
}
src := strings.Join(doc.Lines[b.First():b.Last()+1], "\n") + "\n"
out, err := format.Source([]byte(src))
if err != nil {
continue
}
formatted := strings.Split(strings.TrimRight(string(out), "\n"), "\n")
lines = append(append(append([]string{}, lines[:b.First()]...), formatted...), lines[b.Last()+1:]...)
}
text := strings.Join(lines, "\n") + "\n"
if *write {
if err := os.WriteFile(doc.Path, []byte(text), 0o644); err != nil {
fmt.Fprintln(os.Stderr, "litgo:", err)
return 1
}
return 0
}
fmt.Print(text)
return 0
}
func inlineRefs(lines []string) bool {
for i, l := range lines {
for _, r := range lit.RefsIn(l, i) {
if r.Inline {
return true
}
}
}
return false
}
func cmdAnalyze(args []string) int {
fs := flag.NewFlagSet("analyze", flag.ExitOnError)
path := fs.String("path", "", "the document's file name")
upright := fs.Bool("upright", false, "do not italicise math letters")
fs.Parse(args)
return printJSON(stdinDoc(*path).Analyze(lit.AnalyzeOptions{Upright: *upright}))
}
func cmdUntangle(args []string) int {
fs := flag.NewFlagSet("untangle", flag.ExitOnError)
path := fs.String("path", "", "the document's file name")
start := fs.Int("start", -1, "first selected line")
end := fs.Int("end", -1, "last selected line")
startCol := fs.Int("start-col", 0, "first selected byte (charwise)")
endCol := fs.Int("end-col", -1, "byte after the selection (charwise)")
name := fs.String("name", "", "chunk name; suggested when empty")
fs.Parse(args)
res, err := stdinDoc(*path).Untangle(lit.Selection{StartLine: *start, EndLine: *end, StartCol: *startCol, EndCol: *endCol}, *name)
if err != nil {
return jsonError(err)
}
return printJSON(res)
}
func cmdVersion(args []string) int {
fmt.Printf("%s\n", VERSION)
return 0
}
func cmdRename(args []string) int {
fs := flag.NewFlagSet("rename", flag.ExitOnError)
path := fs.String("path", "", "the document's file name")
from := fs.String("from", "", "current chunk name")
to := fs.String("to", "", "new chunk name")
fs.Parse(args)
edits, err := stdinDoc(*path).Rename(*from, *to)
if err != nil {
return jsonError(err)
}
return printJSON(map[string]any{"edits": edits, "name": lit.NormName(*to)})
}