blue-lang-cli 0.0.288

The blue command line: run, fmt, ast, erase, check.
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
use(
  "mokuroku",
  %i[
    blue_path_roots
    catalog_of
    entries_of_text
    package_text
    pkg_dir
    pkg_entries
    pkg_gloss
    pkg_name
    pkg_needs
    pkg_tests
    pkg_version
    test_blocks_of_text
  ]
)

use("retsu", %i[first flat_map last])

# blue doc: what a name is, where it lives and how it is called.
#
#   blue doc NAME [--file FILE] [--json]
#   blue doc PKG [--json]
#
# NAME is a builtin, `pkg::name`, or a bare name, which is looked up among the
# builtins and every bidama on BLUE_PATH. With --file, the file's own
# definitions are searched too, and each answer's tier is how that file
# reaches the name: `own`, `imported` (a `use` lists it), `qualified` (the
# file uses the package; write `pkg::name`), `not-imported`, or `builtin`.
# PKG, a bidama's name, lists the package.
#
# The tool is blue. It reads the bidamas as mokuroku reads them for the
# catalogue, asks the blue running it for the builtins (`blue reference`) and
# for a file's imports (`blue ast --resolved --json`), and takes a builtin's
# examples from the conformance rows compiled into that blue (`blue doc
# --rows`).

def run_blue(args)
  exec_capture(*cons(self_exe, args))
end

def captured(args)
  r = run_blue(args)
  if r[0][1] != 0
    raise(:doc, "blue #{join(args, " ")}: #{r[2][1]}")
  end
  r[1][1]
end

# The value after `flag` in the arguments, or nil.
def flag_value(args, flag)
  at = filter((i) -> args[i] == flag, range(length(args)))
  if empty?(at) or first(at) + 1 >= length(args)
    nil
  else
    args[first(at) + 1]
  end
end

# ── what is documented ─────────────────────────────────────────────────────

def builtins()
  json_get(json_parse(captured(["reference"])), :names)
end

@doc """
rows_for: Every conformance row that covers the builtin `name` and whose expectation main holds, as `blue doc --rows` gives it: a row that waits on a gap states a destination, so it is never an example.

    length(rows_for("length")) > 0 #=> true
"""
def rows_for(name)
  filter(
    fn(r)
      member?("builtin:#{name}", json_get(r, :covers)) and
        json_get(r, :waits_on).nil?
    end,
    json_parse(captured(%w[doc --rows]))
  )
end

def builtin_entry(b, tier)
  name = json_get(b, :name)
  rows = rows_for(name)
  example = if empty?(rows)
    nil
  else
    row = first(rows)
    {
      from: "spec row #{json_get(row, "id")}",
      code: [json_get(row, :src), "=> #{json_get(row, "expect")}"]
    }
  end
  {
    name:,
    namespace: "blue",
    tier:,
    kind: json_get(b, :arbiter),
    topic: json_get(b, :topic),
    signature: json_get(b, :signature),
    doc: [json_get(b, :doc)],
    example:
  }
end

# Does `line` call `name`: `name(` not preceded by a name character?
def calls?(line, name)
  parts = split(line, "#{name}(")
  length(parts) > 1 and
    any?(
      fn(before)
        cs = chars(before)
        empty?(cs) or not name_char?(cs[length(cs) - 1])
      end,
      take(length(parts) - 1, parts)
    )
end

def name_char?(c)
  contains?(
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_?!:",
    c
  )
end

# The first test in `text` that calls `name`, as an example, or nil.
def test_example(text, name)
  blocks = filter(
    (b) -> any?((l) -> calls?(l, name), last(b)),
    test_blocks_of_text(text)
  )
  if empty?(blocks)
    nil
  else
    b = first(blocks)
    {
      from: "test \"#{first(b)}\"",
      code: map((l) -> blue::trim(l), take(8, last(b)))
    }
  end
end

# The entry for definition `e` ([name, signature, doc_lines, waivers]) of the
# package `pkg` (a mokuroku record, or nil for the file's own script).
def derived_of(pkg, name)
  r = run_blue(
    ["doc", name, "--file", "#{pkg_dir(pkg)}/#{pkg_name(pkg)}.b", "--derived"]
  )
  if r[0][1] == 0
    json_parse(r[1][1])
  end
end

def def_entry(pkg, e, text, tier)
  name = first(e)
  qualifier = if pkg.nil?
    ""
  else
    "#{pkg_name(pkg)}::"
  end
  {
    name: "#{qualifier}#{name}",
    namespace: if pkg.nil?
      nil
    else
      pkg_name(pkg)
    end,
    tier:,
    kind: "definition",
    topic: nil,
    signature: "#{qualifier}#{e[1]}",
    doc: e[2],
    example: test_example(text, name),
    derived: if pkg.nil?
      nil
    else
      derived_of(pkg, name)
    end,
    defaults: if pkg.nil?
      []
    else
      defaults_of(pkg, "#{qualifier}#{name}")
    end
  }
end

@doc """
defaults_of: The defaults rules the definition `qualified` of package `pkg` gets (W7.2 of
docs/FACTS.md), as `blue shift --defaults` decides them from its facts: each
rule that fires, and each that waits on a fact, with the fact it lacks. A
package is every `.b` file directly in its directory.

    defaults_of(["none"], "none::x") #=> []
"""
def defaults_of(pkg, qualified)
  dir = pkg_dir(pkg)
  files = if dir.nil?
    []
  else
    filter((p) -> ends_with?(p, ".b") and path_dirname(p) == dir, walk_dir(dir))
  end
  flat_map(files, (f) -> rules_in(f, qualified))
end

@doc """
rules_in: The rules `blue shift --defaults` decided for `qualified` in the file `f`, or
[] when the file does not check.

    rules_in("no-such-file.b", "x") #=> []
"""
def rules_in(f, qualified)
  r = run_blue(["shift", "--defaults", "--json", f])
  if r[0][1] != 0
    []
  else
    flat_map(
      filter(
        (d) -> json_get(d, :name) == qualified,
        json_get(json_read(r[1][1]), :definitions)
      ),
      (d) -> json_get(d, :rules)
    )
  end
end

@doc """
default_line: one rule `blue shift --defaults` decided for a definition, as `blue doc`
writes it.

    default_line(json_read("{\"rule\": \"R2\", \"fires\": true, \"detail\": \"answered from a table\"}")) #=> "default R2: answered from a table"
    default_line(json_read("{\"rule\": \"R2\", \"fires\": false, \"missing\": \"it is not pure\"}")) #=> "R2 waits on: it is not pure"
"""
def default_line(r)
  if json_get(r, :fires)
    "default #{json_get(r, :rule)}: #{json_get(r, :detail)}"
  else
    "#{json_get(r, :rule)} waits on: #{json_get(r, :missing)}"
  end
end

# ── tiers ──────────────────────────────────────────────────────────────────

# How the file described by `ctx` reaches `name` in package `pkg`.
def tier_in(ctx, pkg, name)
  if ctx.nil?
    "qualified"
  elsif json_get(ctx, :namespace) == pkg
    "own"
  else
    uses = filter((u) -> json_get(u, :package) == pkg, json_get(ctx, :imports))
    if empty?(uses)
      "not-imported"
    elsif any?((u) -> member?(name, json_get(u, :names)), uses)
      "imported"
    else
      "qualified"
    end
  end
end

# ── lookup ─────────────────────────────────────────────────────────────────

def lookup(name, file, records)
  ctx = if file.nil?
    nil
  else
    json_parse(captured(["ast", "--resolved", "--json", file]))
  end
  parts = split(name, "::")
  qualifier = if length(parts) == 2
    first(parts)
  end
  bare = last(parts)
  own = if file.nil? or json_get(ctx, :namespace) != nil
    []
  else
    text = read_file(file)
    map(
      (e) -> def_entry(nil, e, text, "own"),
      filter((e) -> first(e) == bare, entries_of_text(text))
    )
  end
  from_bidamas = flat_map(
    filter((r) -> qualifier.nil? or qualifier == pkg_name(r), records),
    fn(r)
      text = package_text(pkg_dir(r))
      map(
        (e) -> def_entry(r, e, text, tier_in(ctx, pkg_name(r), bare)),
        filter((e) -> first(e) == bare, pkg_entries(r))
      )
    end
  )
  from_builtins = if qualifier.nil? or qualifier == "blue"
    map(
      (b) -> builtin_entry(b, "builtin"),
      filter((b) -> json_get(b, :name) == bare, builtins)
    )
  else
    []
  end
  append(own, from_bidamas, from_builtins)
end

# ── rendering ──────────────────────────────────────────────────────────────

def entry_text(e)
  where = if e[:namespace] == "blue"
    "builtin #{e[:kind]} · #{e[:topic]}"
  elsif e[:namespace].nil?
    "defined in the file"
  else
    "bidama #{e[:namespace]}"
  end
  example = e[:example]
  derived = e[:derived]
  lines = append(
    [e[:signature], "  #{where} · tier: #{e[:tier]}"],
    map((l) -> "  #{l}", e[:doc]),
    if derived.nil?
      []
    else
      map((l) -> "  · #{l}", json_get(derived, :lines))
    end,
    map((r) -> "  · #{default_line(r)}", e[:defaults] or []),
    if example.nil?
      []
    else
      append(
        ["  example (#{example[:from]}):"],
        map((l) -> "    #{l}", example[:code])
      )
    end
  )
  join(lines, line_break)
end

def package_entry(r)
  {
    package: pkg_name(r),
    version: pkg_version(r),
    needs: pkg_needs(r),
    gloss: pkg_gloss(r),
    tests: pkg_tests(r),
    definitions: map(
      fn(e)
        {
          name: first(e),
          signature: e[1],
          doc: if empty?(e[2])
            ""
          else
            first(e[2])
          end
        }
      end,
      pkg_entries(r)
    )
  }
end

def package_text_view(p)
  needs = if empty?(p[:needs])
    "—"
  else
    join(p[:needs], ", ")
  end
  head = [
    "#{p[:package]} #{p[:version]} · needs: #{needs} · #{to_s(p[:tests])} tests",
    "  #{p[:gloss]}",
    ""
  ]
  defs = map(
    fn(d)
      signature = "  #{p[:package]}::#{d[:signature]}"
      if d[:doc] == ""
        signature
      else
        join_lines([signature, "      #{d[:doc]}"])
      end
    end,
    p[:definitions]
  )
  join(append(head, defs), line_break)
end

# What the doc says, written to stdout; true when something was found. The
# binary exits non-zero on false.
def main(args)
  if empty?(args) or starts_with?(first(args), "--")
    raise(:usage, "usage: blue doc NAME [--file FILE] [--json]")
  end
  name = first(args)
  json? = member?("--json", args)
  file = flag_value(args, "--file")
  records = catalog_of(
    blue_path_roots("#{getenv("BLUE_PATH", "")}:#{getenv("BLUE_DIST", "")}")
  )
  packages = filter((r) -> pkg_name(r) == name, records)
  if not contains?(name, "::") and not empty?(packages)
    p = package_entry(first(packages))
    if json?
      write_stdout(unlines([json_stringify(p)]))
    else
      write_stdout(unlines([package_text_view(p)]))
    end
    true
  else
    found = lookup(name, file, records)
    if empty?(found)
      where = if empty?(records)
        "the builtins (BLUE_PATH names no bidama)"
      else
        "the builtins and #{to_s(length(records))} bidamas on BLUE_PATH"
      end
      write_stderr(unlines(["blue doc: no `#{name}` in #{where}"]))
      false
    elsif json?
      map((e) -> write_stdout(unlines([json_stringify(e)])), found)
      true
    else
      write_stdout(unlines([join(map(entry_text, found), unlines(["", ""]))]))
      true
    end
  end
end

main(argv)