Files

171 lines
7.0 KiB
Python

#!/usr/bin/env python3
"""Take 5 §P2's phase: `renametrace`.
The tracker's own note about the tail rename is that *two output files is not
an input count* — nobody could say how many files a rename reads, which rung
asked for them, or which stage of the engine the 780 ms is. §P2a puts the
answer in the server: with `--verbose` the rename logs one
`timing: rename trace …` line carrying the selection (which rung wanted how
many files) and the engine's stages (wall time and **whole-file parses** per
stage). This phase issues the seven renames the plan names, reads that line
back off `window/logMessage`, and writes its fields as row fields so the
tracker can quote them.
Every field the line carries becomes a row field of the same name, so nothing
in the document is read out of prose. `ms` is still the wire latency and
nothing else (schema 2); the trace's own stage times are `trace_*` fields.
Peak RSS is sampled across each rename with `phases_new.Sampler`, the §P0
sampler, so a row says what the request cost in memory as well as in time.
"""
import json
import os
import re
import phases_new
import schema
from harness import (
ARGS, at, counts, edit_of, fingerprint, phase, record, samples, session,
settled, sites,
)
#: `timing: rename trace <fields>` — the whole line the server logs.
TRACE_LINE = re.compile(r"timing: rename trace (.*)$")
#: One `key=value` of it. Braces group a stage's fields (`verify{...}`) and are
#: flattened into `verify_tokens`, `parses_index` and so on.
FIELD = re.compile(r"([a-z_]+)=([^\s{}]+)")
GROUP = re.compile(r"([a-z_]+)\{([^{}]*)\}")
def parse_trace(text):
"""One trace line → a flat dict of numbers, groups flattened by prefix."""
out = {}
for name, body in GROUP.findall(text):
for key, value in FIELD.findall(body):
out["%s_%s" % (name, key)] = number(value)
for key, value in FIELD.findall(GROUP.sub("", text)):
out[key] = number(value)
return out
def number(text):
"""`12`, `3.4ms`, `true` — whatever the line spells, as a number or bool."""
if text in ("true", "false"):
return text == "true"
text = text[:-2] if text.endswith("ms") else text
try:
return int(text)
except ValueError:
pass
try:
return float(text)
except ValueError:
return text
def trace_of(s):
"""The last rename trace this session logged, flattened; `{}` if none.
Read off `window/logMessage`, which `lspclient` captures for exactly this.
A row whose trace is empty is a row whose server was not `--verbose` or
whose request never reached the engine — either way the phase says so
rather than inventing fields.
"""
s.drain()
found = [m for text in s.log_messages for m in TRACE_LINE.findall(text)]
s.log_messages = []
return parse_trace(found[-1]) if found else {}
#: The renames §P2a compares, each `(row, file, needle, occurrence, offset,
#: new_name, also_open)`. The first two are the tracker's own REF rows; the
#: rest are the shapes the plan names — a unique internal name, a common port
#: name, a new name that already exists in scope, a new name a great many
#: external uses already spell, and the two doors to the all-sources fallback.
RENAMES = [
("tail: state_q -> state_q_x",
sites.ENTROPY_SRC_SM, "state_d, state_q;", 1, len("state_d, "),
"state_q_x", sites.ENTROPY_SRC_CORE),
("ordinary: aes -> aes_renamed",
sites.TB, " aes #(", 1, 2, "aes_renamed", None),
("unique internal: cipher_alert -> cipher_alert_x",
sites.AES_CORE, "cipher_alert;", 1, 0, "cipher_alert_x", None),
("common port: clk_i -> clk_ix",
sites.ENTROPY_SRC_SM, "input logic clk_i,", 1,
len("input logic "), "clk_ix", None),
("conflict: state_q -> state_d",
sites.ENTROPY_SRC_SM, "state_d, state_q;", 1, len("state_d, "),
"state_d", sites.ENTROPY_SRC_CORE),
("new name many uses spell: cipher_alert -> clk_i",
sites.AES_CORE, "cipher_alert;", 1, 0, "clk_i", None),
("duplicate module: rstmgr_por -> rstmgr_por_x",
sites.RSTMGR, "rstmgr_por ", 1, 0, "rstmgr_por_x", None),
# TODO §63.1's shape: a net declared in `aes.sv` whose only other
# occurrence is the expression half of a `bind aes …` connection, in a
# file that instantiates nothing in the chain. Before 0.54.0 that
# occurrence was neither edited nor warned about, so this row's edit
# count is what the lane changed.
("bind: entropy_masking_req -> masking_req_x",
sites.AES, "entropy_clearing_req, entropy_masking_req;", 1,
len("entropy_clearing_req, "), "masking_req_x", sites.AES_BIND),
]
@phase("renametrace")
def phase_renametrace():
"""The seven renames, each with the server's own trace beside the wire."""
for row, relative, needle, occurrence, offset, new_name, also in RENAMES:
rename_row(row, relative, needle, occurrence, offset, new_name, also)
no_symbol_row()
def rename_row(row, relative, needle, occurrence, offset, new_name, also):
"""One traced rename, timed on the wire and sampled for peak RSS."""
with session("workspace", verbose=True, storage_name="renametrace") as s:
settled(s)
s.did_open(sites.path(relative))
if also:
s.did_open(sites.path(also))
s.wait_quiet(0.8)
s.take_notifications()
s.log_messages = []
params = dict(at(relative, needle, occurrence, offset), newName=new_name)
sampler = phases_new.Sampler(s.proc.pid)
sampler.start()
got = samples(s, "textDocument/rename", params, ARGS.tries + 1)
peak = sampler.stop()
edit = edit_of(got.last)
trace = trace_of(s)
status = schema.status_of(got.last)
record(phase="renametrace", row=row, client=s.client_shape(),
fingerprint=fingerprint(edit), peak_rss_kib=peak,
file=relative, new_name=new_name,
titles=sorted(os.path.basename(u)
for u in phases_new.edited_uris(got.last)),
note=json.dumps(trace),
**dict(got.row(), **dict(counts(edit), **prefixed(trace))))
def no_symbol_row():
"""The other door to the whole scope: a cursor with no name to fan out
from, which `rename.rs` answers with `ws.sources()` outright."""
with session("workspace", verbose=True, storage_name="renametrace") as s:
settled(s)
s.log_messages = []
params = dict(at(sites.TB, "// ", 1, 1), newName="nothing_here")
sampler = phases_new.Sampler(s.proc.pid)
sampler.start()
got = samples(s, "textDocument/rename", params, ARGS.tries + 1)
peak = sampler.stop()
trace = trace_of(s)
record(phase="renametrace", row="no symbol: whole scope then refuse",
client=s.client_shape(), peak_rss_kib=peak, file=sites.TB,
note=json.dumps(trace), **dict(got.row(), **prefixed(trace)))
def prefixed(trace):
"""The trace's fields, under `trace_` so nothing collides with schema 2."""
return {"trace_%s" % key: value for key, value in trace.items()}