activity.py

clew/wiki/activity.py

A function's activity diagram: its control flow, drawn from its parsed body (round 5, P5.5).

_back_edge

str clew.wiki.activity._back_edge(list[Step] steps, int i, float width)

A loop's back edge, from its body's last step to the loop.

clew/wiki/activity.py:131

Source · 11 lines
def _back_edge(steps: list[Step], i: int, width: float) -> str:
    """@brief Right-hand return path. @return SVG."""
    depth = steps[i].depth
    j = i
    while j + 1 < len(steps) and steps[j + 1].depth > depth:
        j += 1
    x = width - 20 - depth * 6
    y1, y2 = j * _PITCH + 15, i * _PITCH + 15
    return f'<path class="loop-back" d="M{x - 14} {y1} H{x} V{y2} H{x - 14}"/>'

Activity · 7 steps
lines 133–133depth = steps[i].depthlines 134–134j = ilines 135–135◇ while j + 1 < len(steps) and steps[j + 1].depth > depthlines 136–136j += 1lines 137–137x = width - 20 - depth * 6lines 138–138y1, y2 = j * _PITCH + 15, i * _PITCH + 15lines 139–139return f'<path class="loop-back" d="M{x - 14} {y1} H{x} V{y2} H{x - 14}"/>'

Flows

_c_block

None clew.wiki.activity._c_block(node, int depth, int base, list[Step] out)

Emit the steps of one C/C++ block or statement.

clew/wiki/activity.py:317

Source · 35 lines
def _c_block(node, depth: int, base: int, out: list[Step]) -> None:  # noqa: ANN001
    """@brief Recurse into if / loops / blocks. @return None."""
    children = node.named_children if node.type == "compound_statement" else [node]
    for child in children:
        if child.type == "comment":
            continue
        first, last = base + child.start_point[0], base + child.end_point[0]
        if child.type == "if_statement":
            cond = child.child_by_field_name("condition")
            out.append(Step(COND, f"if {_collapse(cond)}", first, base + cond.end_point[0], depth))
            _c_block(child.child_by_field_name("consequence"), depth + 1, base, out)
            alt = child.child_by_field_name("alternative")
            if alt is not None:
                inner = (
                    alt.named_children[0]
                    if alt.type == "else_clause" and alt.named_children
                    else alt
                )
                out.append(
                    Step(ELSE, "else", base + alt.start_point[0], base + alt.start_point[0], depth)
                )
                _c_block(inner, depth + 1, base, out)
        elif child.type in ("for_statement", "while_statement", "do_statement", "for_range_loop"):
            head = _collapse(child).split("{", 1)[0].strip()
            out.append(Step(LOOP, head, first, first, depth))
            loop_body = child.child_by_field_name("body")
            if loop_body is not None:
                _c_block(loop_body, depth + 1, base, out)
        elif child.type == "compound_statement":
            _c_block(child, depth, base, out)
        else:
            kind = EXIT if child.type in ("return_statement", "throw_statement") else STMT
            out.append(Step(kind, _collapse(child), first, last, depth))

Activity · 25 steps
lines 319–319children = node.named_children if node.type == "compound_statement" else [node]lines 320–320◇ for child in childrenlines 321–321◇ if child.type == "comment"lines 322–322continuelines 323–323first, last = base + child.start_point[0], base + child.end_point[0]lines 324–324◇ if child.type == "if_statement"lines 325–325cond = child.child_by_field_name("condition")lines 326–326out.append(Step(COND, f"if {_collapse(cond)}", first, base + cond.end_point[0], depth))lines 327–327_c_block(child.child_by_field_name("consequence"), depth + 1, base, out)lines 328–328alt = child.child_by_field_name("alternative")lines 329–329◇ if alt is not Nonelines 330–334inner = ( alt.named_children[0] if alt.type == "else_clause" and alt.named_children else alt )lines 335–337out.append( Step(ELSE, "else", base + alt.start_point[0], base + alt.start_point[0], depth) )lines 338–338_c_block(inner, depth + 1, base, out)lines 339–339◇ elif child.type in ("for_statement", "while_statement", "do_statement", "for_range_loop")lines 340–340head = _collapse(child).split("{", 1)[0].strip()lines 341–341out.append(Step(LOOP, head, first, first, depth))lines 342–342loop_body = child.child_by_field_name("body")lines 343–343◇ if loop_body is not Nonelines 344–344_c_block(loop_body, depth + 1, base, out)lines 345–345◇ elif child.type == "compound_statement"lines 346–346_c_block(child, depth, base, out)lines 347–347elselines 348–348kind = EXIT if child.type in ("return_statement", "throw_statement") else STMTlines 349–349out.append(Step(kind, _collapse(child), first, last, depth))

Flows

_c_steps

list[Step] clew.wiki.activity._c_steps(list[str] lines, str lang, int first_line)

C and C++ steps through tree-sitter.

clew/wiki/activity.py:280

Source · 12 lines
def _c_steps(lines: list[str], lang: str, first_line: int) -> list[Step]:
    """@brief Find the function's body, then walk it. @return Steps."""
    from ..tsnode import Parser

    root = Parser(lang).parse("\n".join(lines).encode()).root_node
    body = _first(root, "compound_statement")
    out: list[Step] = []
    if body is not None:
        _c_block(body, 0, first_line, out)
    return out

Activity · 7 steps
lines 282–282from ..tsnode import Parserlines 284–284root = Parser(lang).parse("\n".join(lines).encode()).root_nodelines 285–285body = _first(root, "compound_statement")lines 286–286out: list[Step] = []lines 287–287◇ if body is not Nonelines 288–288_c_block(body, 0, first_line, out)lines 289–289return out

Flows

_collapse

str clew.wiki.activity._collapse(node)

A node's text with whitespace collapsed.

clew/wiki/activity.py:357

Show on the map →

Called by _c_block

Calls none

Source · 4 lines
def _collapse(node) -> str:  # noqa: ANN001
    """@brief Decode and collapse. @return Text."""
    raw = node.text.decode("utf-8", errors="replace") if node is not None and node.text else ""
    return " ".join(raw.split())

1 more lines, not shown

Activity · 2 steps
lines 359–359raw = node.text.decode("utf-8", errors="replace") if node is not None and node.text else ""lines 360–360return " ".join(raw.split())

Flows

_edge

str clew.wiki.activity._edge(list[Step] steps, int i)

The connector from one step to the next.

clew/wiki/activity.py:116

Source · 8 lines
def _edge(steps: list[Step], i: int) -> str:
    """@brief A vertical, then horizontal, line between consecutive rows. @return SVG."""
    a, b = steps[i], steps[i + 1]
    x1, x2 = a.depth * _INDENT + _PAD + 6, b.depth * _INDENT + _PAD + 6
    y1, y2 = i * _PITCH + 4 + _H, (i + 1) * _PITCH + 4
    return f'<path class="flow" d="M{x1} {y1} V{y2 - 4} H{x2} V{y2}"/>'

Activity · 4 steps
lines 118–118a, b = steps[i], steps[i + 1]lines 119–119x1, x2 = a.depth * _INDENT + _PAD + 6, b.depth * _INDENT + _PAD + 6lines 120–120y1, y2 = i * _PITCH + 4 + _H, (i + 1) * _PITCH + 4lines 121–121return f'<path class="flow" d="M{x1} {y1} V{y2 - 4} H{x2} V{y2}"/>'

Flows

_first

clew.wiki.activity._first(node, str kind)

The first descendant of a type.

clew/wiki/activity.py:298

Show on the map →

Called by _c_steps

Calls none

Source · 11 lines
def _first(node, kind: str):  # noqa: ANN001, ANN201
    """@brief Breadth-first search. @return Node or None."""
    queue = [node]
    while queue:
        current = queue.pop(0)
        if current.type == kind:
            return current
        queue.extend(current.children)
    return None

Activity · 7 steps
lines 300–300queue = [node]lines 301–301◇ while queuelines 302–302current = queue.pop(0)lines 303–303◇ if current.type == kindlines 304–304return currentlines 305–305queue.extend(current.children)lines 306–306return None

Flows

_node

str clew.wiki.activity._node(Step step, int i)

One step's shape and text.

clew/wiki/activity.py:96

Source · 14 lines
def _node(step: Step, i: int) -> str:
    """@brief Box, diamond-ended box, label, or terminal. @return SVG."""
    x, y = step.depth * _INDENT + _PAD, i * _PITCH + 4
    w = len(step.text) * _CHAR + 2 * _PAD
    radius = {EXIT: 11, ELSE: 0}.get(step.kind, 3)
    marker = "◇ " if step.kind in (COND, LOOP) else ""
    title = f"<title>lines {step.first}–{step.last}</title>"
    return (
        f'<g class="step s-{step.kind}" data-l="{step.first}-{step.last}">{title}'
        f'<rect x="{x}" y="{y}" width="{w:.0f}" height="{_H}" rx="{radius}"/>'
        f'<text x="{x + _PAD}" y="{y + 15}">{marker}{escape(step.text)}</text></g>'
    )

Activity · 6 steps
lines 98–98x, y = step.depth * _INDENT + _PAD, i * _PITCH + 4lines 99–99w = len(step.text) * _CHAR + 2 * _PADlines 100–100radius = {EXIT: 11, ELSE: 0}.get(step.kind, 3)lines 101–101marker = "◇ " if step.kind in (COND, LOOP) else ""lines 102–102title = f"<title>lines {step.first}–{step.last}</title>"lines 103–107return ( f'<g class="step s-{step.kind}" data-l="{step.first}-{step.last}">{title}' f'<rect x="{x}" y="{y}" width="{w:.0f}" height="{_H}" rx="{radius}"/>' f'<text x="{x + _PAD}" y="{y + 15}">{marker}{escape(step.text)}</text></g>' )

Flows

_py_block

None clew.wiki.activity._py_block(list[ast.stmt] body, int depth, str source, int base, list[Step] out)

Emit the steps of one Python block.

clew/wiki/activity.py:185

Source · 24 lines
def _py_block(body: list[ast.stmt], depth: int, source: str, base: int, out: list[Step]) -> None:
    """@brief Recurse into compound statements. @return None."""
    for node in body:
        first, last = base + node.lineno - 1, base + (node.end_lineno or node.lineno) - 1
        header = _py_header(node, source)
        if isinstance(node, ast.If):
            out.append(Step(COND, header, first, base + node.test.end_lineno - 1, depth))
            _py_block(node.body, depth + 1, source, base, out)
            _py_orelse(node, depth, source, base, out)
        elif isinstance(node, (ast.For, ast.AsyncFor, ast.While)):
            out.append(Step(LOOP, header, first, first, depth))
            _py_block(node.body, depth + 1, source, base, out)
        elif isinstance(node, (ast.With, ast.AsyncWith, ast.Try)):
            out.append(Step(STMT, header, first, first, depth))
            _py_block(node.body, depth + 1, source, base, out)
            for handler in getattr(node, "handlers", ()):
                h = base + handler.lineno - 1
                out.append(Step(ELSE, _py_header(handler, source), h, h, depth))
                _py_block(handler.body, depth + 1, source, base, out)
        else:
            kind = EXIT if isinstance(node, (ast.Return, ast.Raise)) else STMT
            out.append(Step(kind, header, first, last, depth))

Activity · 20 steps
lines 187–187◇ for node in bodylines 188–188first, last = base + node.lineno - 1, base + (node.end_lineno or node.lineno) - 1lines 189–189header = _py_header(node, source)lines 190–190◇ if isinstance(node, ast.If)lines 191–191out.append(Step(COND, header, first, base + node.test.end_lineno - 1, depth))lines 192–192_py_block(node.body, depth + 1, source, base, out)lines 193–193_py_orelse(node, depth, source, base, out)lines 194–194◇ elif isinstance(node, (ast.For, ast.AsyncFor, ast.While))lines 195–195out.append(Step(LOOP, header, first, first, depth))lines 196–196_py_block(node.body, depth + 1, source, base, out)lines 197–197◇ elif isinstance(node, (ast.With, ast.AsyncWith, ast.Try))lines 198–198out.append(Step(STMT, header, first, first, depth))lines 199–199_py_block(node.body, depth + 1, source, base, out)lines 200–200◇ for handler in getattr(node, "handlers", ())lines 201–201h = base + handler.lineno - 1lines 202–202out.append(Step(ELSE, _py_header(handler, source), h, h, depth))lines 203–203_py_block(handler.body, depth + 1, source, base, out)lines 204–204elselines 205–205kind = EXIT if isinstance(node, (ast.Return, ast.Raise)) else STMTlines 206–206out.append(Step(kind, header, first, last, depth))

Flows

_py_header

str clew.wiki.activity._py_header(ast.AST node, str source)

The text a step shows: the statement, or a compound statement's header line.

clew/wiki/activity.py:252

Show on the map →

Called by _py_block

Calls none

Source · 21 lines
def _py_header(node: ast.AST, source: str) -> str:
    """@brief Header of a compound statement, else the whole statement. @return Text."""
    text = ast.get_source_segment(source, node) or ""
    compound = isinstance(
        node,
        (
            ast.If,
            ast.For,
            ast.AsyncFor,
            ast.While,
            ast.With,
            ast.AsyncWith,
            ast.Try,
            ast.ExceptHandler,
        ),
    )
    if compound:
        text = text.split("\n", 1)[0].rstrip(":").rstrip()
    return " ".join(text.split())

Activity · 5 steps
lines 254–254text = ast.get_source_segment(source, node) or ""lines 255–267compound = isinstance( node, ( ast.If, ast.For, ast.AsyncFor, ast.While, ast.With, ast.AsyncWith, ast.Try, ast.ExceptHandler, ), )lines 268–268◇ if compoundlines 269–269text = text.split("\n", 1)[0].rstrip(":").rstrip()lines 270–270return " ".join(text.split())

Flows

_py_orelse

None clew.wiki.activity._py_orelse(ast.If node, int depth, str source, int base, list[Step] out)

An if 's alternative: an elif as a condition at the same depth, else a labelled branch.

clew/wiki/activity.py:218

Source · 28 lines
def _py_orelse(node: ast.If, depth: int, source: str, base: int, out: list[Step]) -> None:
    """`ast` RECORDS NO LINE FOR `else:` itself, only for the statement after it, so the keyword's
    line is found by scanning upward from there. An `elif` is an `If` alone in `orelse` whose line
    starts with `elif`: it is drawn as a condition at the same depth, not as `else` then `if`.

    @brief Alternative branch.
    @return None.
    """
    if not node.orelse:
        return
    lines = source.splitlines()
    head = node.orelse[0]
    if len(node.orelse) == 1 and isinstance(head, ast.If):
        if lines[head.lineno - 1].lstrip().startswith("elif"):
            text = "elif " + " ".join((ast.get_source_segment(source, head.test) or "").split())
            out.append(
                Step(COND, text, base + head.lineno - 1, base + head.test.end_lineno - 1, depth)
            )
            _py_block(head.body, depth + 1, source, base, out)
            _py_orelse(head, depth, source, base, out)
            return
    row = head.lineno - 1
    while row > node.body[-1].end_lineno - 1 and not lines[row].lstrip().startswith("else"):
        row -= 1
    out.append(Step(ELSE, "else", base + row, base + row, depth))
    _py_block(node.orelse, depth + 1, source, base, out)

Activity · 16 steps
lines 226–226◇ if not node.orelselines 227–227returnlines 228–228lines = source.splitlines()lines 229–229head = node.orelse[0]lines 230–230◇ if len(node.orelse) == 1 and isinstance(head, ast.If)lines 231–231◇ if lines[head.lineno - 1].lstrip().startswith("elif")lines 232–232text = "elif " + " ".join((ast.get_source_segment(source, head.test) or "").split())lines 233–235out.append( Step(COND, text, base + head.lineno - 1, base + head.test.end_lineno - 1, depth) )lines 236–236_py_block(head.body, depth + 1, source, base, out)lines 237–237_py_orelse(head, depth, source, base, out)lines 238–238returnlines 239–239row = head.lineno - 1lines 240–240◇ while row > node.body[-1].end_lineno - 1 and not lines[row].lstrip().startswith("else")lines 241–241row -= 1lines 242–242out.append(Step(ELSE, "else", base + row, base + row, depth))lines 243–243_py_block(node.orelse, depth + 1, source, base, out)

Flows

_py_steps

list[Step] clew.wiki.activity._py_steps(list[str] lines, int first_line)

Python steps through ast .

clew/wiki/activity.py:148

Source · 16 lines
def _py_steps(lines: list[str], first_line: int) -> list[Step]:
    """@brief Parse, then walk the function's body. @return Steps."""
    source = textwrap.dedent("\n".join(lines))
    try:
        tree = ast.parse(source)
    except SyntaxError:
        return []
    func = next(
        (n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))), None
    )
    out: list[Step] = []
    if func is not None:
        _py_block(_without_docstring(func.body), 0, source, first_line, out)
    return out

Activity · 10 steps
lines 150–150source = textwrap.dedent("\n".join(lines))lines 151–151trylines 152–152tree = ast.parse(source)lines 153–153except SyntaxErrorlines 154–154return []lines 155–157func = next( (n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))), None )lines 158–158out: list[Step] = []lines 159–159◇ if func is not Nonelines 160–160_py_block(_without_docstring(func.body), 0, source, first_line, out)lines 161–161return out

Flows

_without_docstring

list[ast.stmt] clew.wiki.activity._without_docstring(list[ast.stmt] body)

A body without its leading docstring.

clew/wiki/activity.py:169

Show on the map →

Called by _py_steps

Calls none

Source · 7 lines
def _without_docstring(body: list[ast.stmt]) -> list[ast.stmt]:
    """@brief Drop a leading string expression. @return Body."""
    first = body[0] if body else None
    is_doc = isinstance(first, ast.Expr) and isinstance(getattr(first, "value", None), ast.Constant)
    return body[1:] if is_doc and isinstance(first.value.value, str) else body

Activity · 3 steps
lines 171–171first = body[0] if body else Nonelines 172–172is_doc = isinstance(first, ast.Expr) and isinstance(getattr(first, "value", None), ast.Constant)lines 173–173return body[1:] if is_doc and isinstance(first.value.value, str) else body

Flows

activity_svg

str clew.wiki.activity.activity_svg(list[Step] steps, str label)

The SVG for a function's steps.

clew/wiki/activity.py:74

Source · 16 lines
def activity_svg(steps: list[Step], label: str) -> str:
    """@brief Rows top to bottom, indented by depth, loop back edges on the right. @return SVG."""
    if not steps:
        return ""
    width = max(s.depth * _INDENT + len(s.text) * _CHAR + 3 * _PAD for s in steps) + 40
    height = _PITCH * len(steps) + _PAD
    parts = [_edge(steps, i) for i in range(len(steps) - 1)]
    parts += [_back_edge(steps, i, width) for i, s in enumerate(steps) if s.kind == LOOP]
    parts += [_node(s, i) for i, s in enumerate(steps)]
    return (
        f'<svg class="activity" role="img" aria-label="activity of {escape(label)}: '
        f'{len(steps)} steps" viewBox="0 0 {width:.0f} {height}" width="{width:.0f}" '
        f'height="{height}">' + "".join(parts) + "</svg>"
    )

Activity · 8 steps
lines 76–76◇ if not stepslines 77–77return ""lines 78–78width = max(s.depth * _INDENT + len(s.text) * _CHAR + 3 * _PAD for s in steps) + 40lines 79–79height = _PITCH * len(steps) + _PADlines 80–80parts = [_edge(steps, i) for i in range(len(steps) - 1)]lines 81–81parts += [_back_edge(steps, i, width) for i, s in enumerate(steps) if s.kind == LOOP]lines 82–82parts += [_node(s, i) for i, s in enumerate(steps)]lines 83–87return ( f'<svg class="activity" role="img" aria-label="activity of {escape(label)}: ' f'{len(steps)} steps" viewBox="0 0 {width:.0f} {height}" width="{width:.0f}" ' f'height="{height}">' + "".join(parts) + "</svg>" )

Requirements

REQ-DDB-WIKI-045

Flows

steps_of

list[Step] clew.wiki.activity.steps_of(list[str] lines, str rel, int first_line)

A function's steps, from its source lines.

clew/wiki/activity.py:60

Source · 8 lines
def steps_of(lines: list[str], rel: str, first_line: int) -> list[Step]:
    """@brief Dispatch by language. @return Steps."""
    suffix = PurePosixPath(rel).suffix
    if suffix == ".py":
        return _py_steps(lines, first_line)
    return _c_steps(lines, _C[suffix], first_line) if suffix in _C else []

Activity · 4 steps
lines 62–62suffix = PurePosixPath(rel).suffixlines 63–63◇ if suffix == ".py"lines 64–64return _py_steps(lines, first_line)lines 65–65return _c_steps(lines, _C[suffix], first_line) if suffix in _C else []

Requirements

REQ-DDB-WIKI-045

Flows