diff --git a/explain_my_code/analysis/complexity.py b/explain_my_code/analysis/complexity.py index 4e6c959..e4fea86 100644 --- a/explain_my_code/analysis/complexity.py +++ b/explain_my_code/analysis/complexity.py @@ -9,6 +9,7 @@ from __future__ import annotations import re +from collections.abc import Iterator from dataclasses import dataclass from explain_my_code.ir import CALLABLE_KINDS, LOOP_KINDS, Kind, Node @@ -19,7 +20,16 @@ #: Memoisation markers. The difference between O(2^n) and O(n) for naive fib. MEMO_DECORATORS = ("lru_cache", "cache", "memoize", "functools.cache") -COST_ORDER = ["1", "log n", "n", "n log n", "n²", "n³", "2^n"] +#: Child links of a tree node. Recursing on these walks a tree, visiting each node once, +#: rather than growing a call tree that doubles at every level. +TREE_CHILD = re.compile( + r"(\.|->)\s*(left|right|lhs|rhs|children|child|kids|subtrees?)\b", re.IGNORECASE +) + +#: (power of n, power of log n) for each known library cost. +COST_TERMS: dict[str, tuple[int, int]] = { + "1": (0, 0), "log n": (0, 1), "n": (1, 0), "n log n": (1, 1), +} SUPERSCRIPT = {2: "²", 3: "³", 4: "⁴", 5: "⁵", 6: "⁶"} @@ -64,21 +74,67 @@ def visit(node: Node, depth: int) -> None: return deepest, culprit -def _costly_call_in_loop(function: Node) -> tuple[str, str] | None: - """A known super-linear library call executed inside a loop.""" - best: tuple[str, str] | None = None - for node in function.walk(): - if node.kind not in {Kind.CALL, Kind.METHOD_CALL}: - continue - cost = str(node.meta.get("cost") or "") - if not cost or cost == "1": +def _own_nodes(function: Node) -> Iterator[Node]: + """This function's body, pre-order, without descending into nested callables.""" + stack = list(reversed(function.children)) + while stack: + node = stack.pop() + if node.kind in CALLABLE_KINDS: continue - if node.loop_depth == 0 and cost not in {"n log n", "n"}: + yield node + stack.extend(reversed(node.children)) + + +@dataclass(slots=True) +class _CostlyCall: + callee: str + cost: str + #: Loops of this function the call actually runs inside. + loops: list[Node] + + @property + def term(self) -> tuple[int, int]: + poly, log = COST_TERMS[self.cost] + return poly + len(self.loops), log + + +def _costly_calls(function: Node) -> list[_CostlyCall]: + """Known-cost library calls in this function's own body, with the loops around each. + + A for-each loop evaluates its iterable once, so `for x in sorted(xs)` sorts once: + a call inside the loop's header span is not counted as running inside the loop. + """ + out: list[_CostlyCall] = [] + stack: list[tuple[Node, list[Node]]] = [(c, []) for c in reversed(function.children)] + while stack: + node, loops = stack.pop() + if node.kind in CALLABLE_KINDS: continue - callee = str(node.meta.get("callee") or node.name or "a call") - if best is None or COST_ORDER.index(cost) > COST_ORDER.index(best[0]): - best = (cost, callee) - return best + if node.kind in {Kind.CALL, Kind.METHOD_CALL}: + cost = str(node.meta.get("cost") or "") + if cost in COST_TERMS and cost != "1": + callee = str(node.meta.get("callee") or node.name or "a call") + out.append(_CostlyCall(callee, cost, loops)) + for child in reversed(node.children): + inside = node.kind in LOOP_KINDS and not ( + node.kind is Kind.LOOP_FOREACH and node.span.contains(child.span) + ) + stack.append((child, [*loops, node] if inside else loops)) + return out + + +def _label(term: tuple[int, int]) -> str: + poly, log = term + if poly == 0: + return "log n" if log else "1" + return f"{_loop_label(poly)} log n" if log else _loop_label(poly) + + +def _loop_phrase(depth: int, loop: Node | None) -> str: + iterable = "the input" + if loop is not None: + iterable = str(loop.meta.get("iterable") or loop.meta.get("condition") or "the input") + return f"{depth} nested loop(s) over {iterable}" if depth > 1 else f"one loop over {iterable}" def _is_memoized(function: Node) -> bool: @@ -94,44 +150,127 @@ def _is_memoized(function: Node) -> bool: return False -def _self_call_count(function: Node, name: str) -> int: - count = 0 - for node in function.walk(): - if node.kind in {Kind.CALL, Kind.METHOD_CALL} and node.meta.get("callee") == name: - count += 1 - return count +def _self_calls(function: Node, name: str) -> list[Node]: + return [ + node + for node in _own_nodes(function) + if node.kind in {Kind.CALL, Kind.METHOD_CALL} and node.meta.get("callee") == name + ] + +def _calls_per_invocation(function: Node, calls: list[Node]) -> int: + """Self-calls one invocation can make, not how many are written down. -def _recursive_estimate(function: Node, name: str) -> ComplexityEstimate | None: - calls = _self_call_count(function, name) - if calls == 0: + A call returns through at most one `return`, so calls sitting in different return + statements are alternatives: recursive binary search has two, and makes one. + """ + per_return: dict[int, int] = {} + elsewhere = 0 + for call in calls: + owner = next( + (a for a in call.ancestors() if a is function or a.kind is Kind.RETURN), None + ) + if owner is None or owner is function: + elsewhere += 1 + else: + per_return[owner.id] = per_return.get(owner.id, 0) + 1 + return elsewhere + max(per_return.values(), default=0) + + +def _shrinks_by_a_constant(function: Node, args: str) -> bool: + """`n - 1`, `i + 1`, `s[1:]`: a parameter stepping by a constant, so the recursion + is about n deep. With two or more calls per level that is what makes it exponential.""" + params = [re.escape(str(p)) for p in function.meta.get("param_names") or [] if p] + name = f"(?:{'|'.join(params)})" if params else r"\w+" + step = rf"\b{name}\s*[-+]\s*\d+\b|\b{name}\s*\[\s*\d+\s*:|\b{name}\s*\[\s*:\s*-\s*\d+\s*\]" + return bool(re.search(step, args)) + + +def _recursive_estimate(function: Node, name: str) -> tuple[ComplexityEstimate, bool] | None: + """The recursion's own cost, and whether that already covers the body's loops.""" + calls = _self_calls(function, name) + if not calls: return None if _is_memoized(function): - return ComplexityEstimate( - "O(n)", - f"`{name}` recurses but memoises, so each distinct input is computed once.", - 0.6, + return ( + ComplexityEstimate( + "O(n)", + f"`{name}` recurses but memoises, so each distinct input is computed once.", + 0.6, + ), + False, ) - if calls >= 2: - return ComplexityEstimate( - f"O({calls}^n)" if calls > 2 else "O(2^n)", - f"`{name}` calls itself {calls} times per invocation with no memoisation, " - "so the call tree doubles at every level.", - 0.75, + branching = _calls_per_invocation(function, calls) + args = " ".join(" ".join(str(a) for a in call.meta.get("args") or []) for call in calls) + walks_a_tree = bool(TREE_CHILD.search(args)) + halves = bool(HALVING.search(args)) + + if branching >= 2: + if walks_a_tree: + return ( + ComplexityEstimate( + "O(n)", + f"`{name}` recurses into each child of a tree node, so it visits every " + "node once.", + 0.6, + ), + True, + ) + if halves: + return ( + ComplexityEstimate( + "O(n log n)", + f"`{name}` splits its input in half and recurses on both halves (divide " + "and conquer, like merge sort): log n levels of O(n) work.", + 0.55, + ), + True, + ) + if _shrinks_by_a_constant(function, args): + return ( + ComplexityEstimate( + f"O({branching}^n)" if branching > 2 else "O(2^n)", + f"`{name}` calls itself {branching} times per invocation with no " + "memoisation, so the call tree doubles at every level.", + 0.75, + ), + True, + ) + return ( + ComplexityEstimate( + "O(n log n)", + f"`{name}` calls itself {branching} times on separate parts of its input " + "(divide and conquer, like quicksort): about O(n log n) when the parts are " + "balanced, O(n²) when they are not.", + 0.4, + ), + True, ) - body = " ".join( - str(node.meta.get("args", "")) + str(node.meta.get("value", "")) - for node in function.walk() - if node.kind in {Kind.CALL, Kind.METHOD_CALL} - ) - if HALVING.search(body): - return ComplexityEstimate( - "O(log n)", - f"`{name}` recurses once per call and halves its input each time.", - 0.7, + + if walks_a_tree: + return ( + ComplexityEstimate( + "O(log n)", + f"`{name}` follows one child per call, so it costs the height of the tree: " + "O(log n) when the tree is balanced, O(n) when it is not.", + 0.5, + ), + False, + ) + if halves: + return ( + ComplexityEstimate( + "O(log n)", + f"`{name}` recurses once per call and halves its input each time.", + 0.7, + ), + False, ) - return ComplexityEstimate( - "O(n)", f"`{name}` recurses once per call, shrinking its input by a constant.", 0.65 + return ( + ComplexityEstimate( + "O(n)", f"`{name}` recurses once per call, shrinking its input by a constant.", 0.65 + ), + False, ) @@ -140,8 +279,8 @@ def estimate(function: Node, *, is_recursive: bool = False) -> ComplexityEstimat name = function.name or "" if is_recursive: - recursive = _recursive_estimate(function, name) - if recursive is None: + result = _recursive_estimate(function, name) + if result is None: # Recursive per the call graph but with no direct self-call: the cycle runs # through another function, so the depth is not visible from this body alone. return ComplexityEstimate( @@ -150,51 +289,51 @@ def estimate(function: Node, *, is_recursive: bool = False) -> ComplexityEstimat "so its cost depends on how fast that cycle shrinks its input.", 0.4, ) + recursive, covers_loops = result depth, _ = _max_loop_depth(function) - if depth > 0 and recursive.label.startswith("O(2^n"): + if covers_loops or depth == 0: return recursive - if depth > 0: - return ComplexityEstimate( - f"O({_loop_label(depth)} · recursion)", - f"{recursive.reason} It also loops {depth} level(s) deep per call.", - 0.5, - ) - return recursive + return ComplexityEstimate( + f"O({_loop_label(depth)} · recursion)", + f"{recursive.reason} It also loops {depth} level(s) deep per call.", + 0.5, + ) depth, culprit = _max_loop_depth(function) - costly = _costly_call_in_loop(function) + costly = max(_costly_calls(function), key=lambda call: call.term, default=None) if depth == 0: if costly is not None: return ComplexityEstimate( - f"O({costly[0]})", - f"No loops here, but `{costly[1]}` costs O({costly[0]}) on its own.", + f"O({costly.cost})", + f"No loops here, but `{costly.callee}` costs O({costly.cost}) on its own.", 0.6, ) return ComplexityEstimate( "O(1)", "No loops and no recursion. The work does not grow with the input.", 0.8 ) - label = _loop_label(depth) - iterable = str(culprit.meta.get("iterable") or culprit.meta.get("condition") or "the input") if culprit else "the input" - reason = ( - f"{depth} nested loop(s) over {iterable}" - if depth > 1 - else f"one loop over {iterable}" - ) - - if costly is not None and costly[0] == "n log n": - combined = f"O({label} log n)" if depth >= 1 else "O(n log n)" + loops_only = (depth, 0) + if costly is None or costly.term <= loops_only: return ComplexityEstimate( - combined, - f"{reason}, and `{costly[1]}` sorts inside it at O(n log n).", - 0.55, + f"O({_label(loops_only)})", + f"{_loop_phrase(depth, culprit)}.", + 0.7 if depth <= 2 else 0.6, ) - if costly is not None and costly[0] == "n": + + label = f"O({_label(costly.term)})" + if not costly.loops: return ComplexityEstimate( - f"O({_loop_label(depth + 1)})", - f"{reason}, and `{costly[1]}` scans the whole collection inside it.", + label, + f"{_loop_phrase(depth, culprit)}, but `{costly.callee}` costs O({costly.cost}) " + "on its own, which dominates.", 0.55, ) - - return ComplexityEstimate(f"O({label})", f"{reason}.", 0.7 if depth <= 2 else 0.6) + where = _loop_phrase(len(costly.loops), costly.loops[-1]) + if costly.cost == "n log n": + detail = f"`{costly.callee}` sorts inside it at O(n log n)" + elif costly.cost == "n": + detail = f"`{costly.callee}` scans the whole collection inside it" + else: + detail = f"`{costly.callee}` costs O({costly.cost}) inside it" + return ComplexityEstimate(label, f"{where}, and {detail}.", 0.55) diff --git a/tests/test_analysis.py b/tests/test_analysis.py index 87d8b2c..5c8447f 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -143,6 +143,159 @@ def process(groups): assert "log n" in function(analysis, "process").complexity_class +MERGE_SORT = """ +def merge_sort(xs): + if len(xs) <= 1: + return xs + mid = len(xs) // 2 + left = merge_sort(xs[:mid]) + right = merge_sort(xs[mid:]) + return merge(left, right) +""" + + +@pytest.mark.parametrize( + "language,source,name,expected", + [ + (Language.PYTHON, MERGE_SORT, "merge_sort", "O(n log n)"), + (Language.PYTHON, """ +def quicksort(xs): + if len(xs) <= 1: + return xs + pivot = xs[0] + left = [x for x in xs[1:] if x < pivot] + right = [x for x in xs[1:] if x >= pivot] + return quicksort(left) + [pivot] + quicksort(right) +""", "quicksort", "O(n log n)"), + (Language.PYTHON, """ +def quicksort(arr, lo, hi): + if lo < hi: + p = partition(arr, lo, hi) + quicksort(arr, lo, p - 1) + quicksort(arr, p + 1, hi) +""", "quicksort", "O(n log n)"), + (Language.PYTHON, """ +def search(xs, lo, hi, target): + if lo > hi: + return -1 + mid = (lo + hi) // 2 + if xs[mid] < target: + return search(xs, mid + 1, hi, target) + return search(xs, lo, mid - 1, target) +""", "search", "O(log n)"), + (Language.PYTHON, """ +def height(node): + if node is None: + return 0 + return 1 + max(height(node.left), height(node.right)) +""", "height", "O(n)"), + (Language.PYTHON, """ +def find(node, key): + if node is None or node.key == key: + return node + if key < node.key: + return find(node.left, key) + return find(node.right, key) +""", "find", "O(log n)"), + (Language.JAVASCRIPT, """ +function mergeSort(a) { + if (a.length <= 1) return a; + const mid = Math.floor(a.length / 2); + return merge(mergeSort(a.slice(0, mid)), mergeSort(a.slice(mid))); +} +""", "mergeSort", "O(n log n)"), + (Language.JAVASCRIPT, """ +function size(node) { + if (!node) return 0; + return 1 + size(node.left) + size(node.right); +} +""", "size", "O(n)"), + (Language.CPP, """ +int count(Node* n) { + if (!n) return 0; + return 1 + count(n->left) + count(n->right); +} +""", "count", "O(n)"), + ], + ids=["merge-sort", "quicksort", "quicksort-in-place", "binary-search", "tree-height", + "bst-find", "js-merge-sort", "js-tree-size", "cpp-tree-count"], +) +def test_divide_and_conquer_and_tree_recursion_are_not_exponential(language, source, name, expected): + """Two self-calls only blow up when each one shrinks the input by a constant. Halves, + partitions and tree children each get visited once, and calls in separate `return`s + never both run.""" + analysis = analyze(source, language) + assert function(analysis, name).complexity_class == expected + assert "exponential-recursion" not in rules(analysis) + + +@pytest.mark.parametrize( + "language,source,name,expected", + [ + (Language.PYTHON, """ +def hanoi(n, a, b, c): + if n == 0: + return + hanoi(n - 1, a, c, b) + print(a, c) + hanoi(n - 1, b, a, c) +""", "hanoi", "O(2^n)"), + (Language.PYTHON, """ +def paths(i, j): + if i == 0 or j == 0: + return 1 + return paths(i - 1, j) + paths(i, j - 1) +""", "paths", "O(2^n)"), + (Language.PYTHON, """ +def decode(s): + if not s: + return 1 + total = decode(s[1:]) + if len(s) > 1 and s[:2] < "27": + total += decode(s[2:]) + return total +""", "decode", "O(2^n)"), + (Language.PYTHON, """ +def trib(n): + if n < 3: + return 1 + return trib(n - 1) + trib(n - 2) + trib(n - 3) +""", "trib", "O(3^n)"), + (Language.JAVASCRIPT, "function fib(n) {\n return n < 2 ? n : fib(n - 1) + fib(n - 2);\n}\n", + "fib", "O(2^n)"), + ], + ids=["hanoi", "grid-paths", "decode-ways", "tribonacci", "js-fib"], +) +def test_constant_step_branching_recursion_stays_exponential(language, source, name, expected): + analysis = analyze(source, language) + assert function(analysis, name).complexity_class == expected + assert "exponential-recursion" in rules(analysis) + + +@pytest.mark.parametrize( + "language,source,expected", + [ + (Language.PYTHON, "def f(xs):\n total = sum(xs)\n for x in xs:\n print(x / total)\n", + "O(n)"), + (Language.PYTHON, + "def f(xs):\n ys = sorted(xs)\n for a in ys:\n for b in ys:\n print(a, b)\n", + "O(n²)"), + (Language.PYTHON, "def f(xs):\n for x in sorted(xs):\n print(x)\n", "O(n log n)"), + (Language.PYTHON, "def f(xs):\n for x in xs:\n print(max(xs))\n", "O(n²)"), + (Language.PYTHON, + "def f(groups):\n out = []\n for g in groups:\n out.append(sorted(g))\n return out\n", + "O(n² log n)"), + (Language.JAVASCRIPT, + "function f(xs) {\n for (const x of xs.filter(Boolean)) {\n console.log(x);\n }\n}\n", + "O(n)"), + ], + ids=["linear-call-before-loop", "sort-before-nested-loops", "sorted-iterable", + "scan-inside-loop", "sort-inside-loop", "js-filtered-iterable"], +) +def test_library_costs_only_multiply_the_loops_they_run_inside(language, source, expected): + assert function(analyze(source, language), "f").complexity_class == expected + + # -- call graph --------------------------------------------------------------------