outliner-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- outliner/__init__.py +1 -0
- outliner/cli.py +115 -0
- outliner/parsers/__init__.py +36 -0
- outliner/parsers/asciidoc.py +89 -0
- outliner/parsers/c.py +281 -0
- outliner/parsers/clojure.py +238 -0
- outliner/parsers/csharp.py +243 -0
- outliner/parsers/go.py +66 -0
- outliner/parsers/java.py +102 -0
- outliner/parsers/javascript.py +312 -0
- outliner/parsers/markdown.py +153 -0
- outliner/parsers/orgmode.py +120 -0
- outliner/parsers/perl.py +100 -0
- outliner/parsers/php.py +90 -0
- outliner/parsers/python.py +73 -0
- outliner/parsers/rst.py +102 -0
- outliner/parsers/ruby.py +88 -0
- outliner/parsers/rust.py +82 -0
- outliner/parsers/scala.py +127 -0
- outliner/parsers/shell.py +62 -0
- outliner/parsers/swift.py +116 -0
- outliner/parsers/util.py +58 -0
- outliner/parsers/zig.py +103 -0
- outliner/types.py +8 -0
- outliner_cli-0.1.0.dist-info/METADATA +126 -0
- outliner_cli-0.1.0.dist-info/RECORD +30 -0
- outliner_cli-0.1.0.dist-info/WHEEL +5 -0
- outliner_cli-0.1.0.dist-info/entry_points.txt +2 -0
- outliner_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- outliner_cli-0.1.0.dist-info/top_level.txt +1 -0
outliner/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
outliner/cli.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""outliner — print structural outline of source files."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from outliner.parsers import NAMES, EXTENSIONS, detect, outline
|
|
9
|
+
from outliner.types import OutlineItem
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def guess_syntax(src: str) -> str | None:
|
|
13
|
+
return EXTENSIONS.get(os.path.splitext(src.lower())[1])
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _expand_sources(sources: list[str]) -> list[str]:
|
|
17
|
+
result = []
|
|
18
|
+
for src in sources:
|
|
19
|
+
if src == "-" or not os.path.isdir(src):
|
|
20
|
+
result.append(src)
|
|
21
|
+
continue
|
|
22
|
+
for root, dirs, files in os.walk(src):
|
|
23
|
+
dirs.sort()
|
|
24
|
+
for name in sorted(files):
|
|
25
|
+
if os.path.splitext(name.lower())[1] in EXTENSIONS:
|
|
26
|
+
result.append(os.path.join(root, name))
|
|
27
|
+
return result
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _format_items(items: list[OutlineItem], grep: re.Pattern | None) -> list[str]:
|
|
31
|
+
if grep:
|
|
32
|
+
items = [it for it in items if grep.search(it.signature)]
|
|
33
|
+
if not items:
|
|
34
|
+
return []
|
|
35
|
+
|
|
36
|
+
max_start_width = max(3, max(len(str(it.start)) for it in items))
|
|
37
|
+
max_field_width = 2 * max_start_width + 1
|
|
38
|
+
|
|
39
|
+
lines = []
|
|
40
|
+
for it in items:
|
|
41
|
+
start_str = str(it.start).rjust(max_start_width)
|
|
42
|
+
combined = f"{start_str},{it.count}"
|
|
43
|
+
lines.append(f"{combined.ljust(max_field_width)} {it.signature}")
|
|
44
|
+
return lines
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def main(argv: list[str] | None = None) -> int:
|
|
48
|
+
ap = argparse.ArgumentParser(
|
|
49
|
+
prog="outliner",
|
|
50
|
+
description="Print the structural outline of source files.",
|
|
51
|
+
)
|
|
52
|
+
ap.add_argument("files", nargs="*", metavar="FILE",
|
|
53
|
+
help="Files to outline (omit or use - for stdin)")
|
|
54
|
+
ap.add_argument("-g", "--grep", metavar="EXPR",
|
|
55
|
+
help="Only show items whose signature matches EXPR (case-insensitive)")
|
|
56
|
+
ap.add_argument("-s", "--syntax", metavar="LANG",
|
|
57
|
+
help=f"Override syntax auto-detection (available: {', '.join(NAMES)})")
|
|
58
|
+
args = ap.parse_args(argv)
|
|
59
|
+
|
|
60
|
+
grep_re: re.Pattern | None = None
|
|
61
|
+
if args.grep:
|
|
62
|
+
try:
|
|
63
|
+
grep_re = re.compile(args.grep, re.IGNORECASE)
|
|
64
|
+
except re.error as exc:
|
|
65
|
+
print(f"outliner: invalid --grep expression: {exc}", file=sys.stderr)
|
|
66
|
+
return 2
|
|
67
|
+
|
|
68
|
+
sources = args.files or ["-"]
|
|
69
|
+
if sources == ["-"] and sys.stdin.isatty():
|
|
70
|
+
ap.print_help()
|
|
71
|
+
return 0
|
|
72
|
+
sources = _expand_sources(sources)
|
|
73
|
+
multi = len(sources) > 1
|
|
74
|
+
|
|
75
|
+
exit_code = 0
|
|
76
|
+
for src in sources:
|
|
77
|
+
try:
|
|
78
|
+
if src == "-":
|
|
79
|
+
text = sys.stdin.read()
|
|
80
|
+
else:
|
|
81
|
+
with open(src, encoding="utf-8", errors="replace") as fh:
|
|
82
|
+
text = fh.read()
|
|
83
|
+
except OSError as exc:
|
|
84
|
+
print(f"outliner: {exc}", file=sys.stderr)
|
|
85
|
+
exit_code = 1
|
|
86
|
+
continue
|
|
87
|
+
|
|
88
|
+
syntax = args.syntax or guess_syntax(src) or detect(text)
|
|
89
|
+
|
|
90
|
+
if syntax is None:
|
|
91
|
+
print(f"outliner: cannot auto-detect syntax for '{src}'; use --syntax",
|
|
92
|
+
file=sys.stderr)
|
|
93
|
+
exit_code = 2
|
|
94
|
+
continue
|
|
95
|
+
|
|
96
|
+
items = outline(syntax, text)
|
|
97
|
+
if items is None:
|
|
98
|
+
available = ", ".join(NAMES)
|
|
99
|
+
print(f"outliner: unsupported syntax '{syntax}'; available: {available}",
|
|
100
|
+
file=sys.stderr)
|
|
101
|
+
exit_code = 2
|
|
102
|
+
continue
|
|
103
|
+
|
|
104
|
+
output_lines = _format_items(items, grep_re)
|
|
105
|
+
|
|
106
|
+
if output_lines:
|
|
107
|
+
if multi:
|
|
108
|
+
print(f"\n==> {src} <==")
|
|
109
|
+
print("\n".join(output_lines))
|
|
110
|
+
|
|
111
|
+
return exit_code
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
if __name__ == "__main__":
|
|
115
|
+
sys.exit(main())
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from . import python, scala, go, java, rust, swift, c, ruby, php, shell, javascript, csharp, perl, zig, clojure, asciidoc, orgmode, rst, markdown
|
|
4
|
+
from outliner.types import OutlineItem
|
|
5
|
+
|
|
6
|
+
_MODULES = [python, scala, go, java, rust, swift, c, ruby, php, shell, javascript, csharp, perl, zig, clojure, asciidoc, orgmode, rst, markdown]
|
|
7
|
+
_PARSERS = {mod.SYNTAX: mod.parse for mod in _MODULES}
|
|
8
|
+
NAMES = sorted(_PARSERS)
|
|
9
|
+
EXTENSIONS = {ext: mod.SYNTAX for mod in _MODULES for ext in mod.EXTENSIONS}
|
|
10
|
+
|
|
11
|
+
_FRONTMATTER_RE = re.compile(r'\A(?:---\n(?:.*\n){0,98}?---\n|\+\+\+\n(?:.*\n){0,98}?\+\+\+\n)')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _strip_frontmatter(content: str) -> str:
|
|
15
|
+
m = _FRONTMATTER_RE.match(content)
|
|
16
|
+
return content[m.end():] if m else content
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def detect(content: str) -> str | None:
|
|
20
|
+
lines = _strip_frontmatter(content).splitlines()[:100]
|
|
21
|
+
for mod in _MODULES:
|
|
22
|
+
if mod.detect(lines):
|
|
23
|
+
return mod.SYNTAX
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def outline(syntax: str, content: str) -> list[OutlineItem] | None:
|
|
28
|
+
parse = _PARSERS.get(syntax)
|
|
29
|
+
if not parse:
|
|
30
|
+
return None
|
|
31
|
+
m = _FRONTMATTER_RE.match(content)
|
|
32
|
+
if not m:
|
|
33
|
+
return list(parse(content))
|
|
34
|
+
offset = m.group(0).count('\n')
|
|
35
|
+
return [OutlineItem(start=it.start + offset, count=it.count, signature=it.signature)
|
|
36
|
+
for it in parse(content[m.end():])]
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""AsciiDoc outline parser.
|
|
2
|
+
|
|
3
|
+
Recognises ATX-style headings prefixed with one or more `=` characters
|
|
4
|
+
followed by a space (``= Title``, ``== Section``, ``=== Subsection``, …).
|
|
5
|
+
The number of `=` signs determines the heading level; level 0 (`=`) is
|
|
6
|
+
the document title. Each heading's range extends to the line before the
|
|
7
|
+
next heading at the same or higher level (lower `=` count), or to EOF.
|
|
8
|
+
|
|
9
|
+
Content detection looks for AsciiDoc-specific co-occurring markers:
|
|
10
|
+
- a document-title line (``= `` at column 0) together with attribute
|
|
11
|
+
entries (``:attr:`` lines) or block macros (``[source,…]``, ``[NOTE]``,
|
|
12
|
+
``[TIP]``, etc.)
|
|
13
|
+
- block macros alone are sufficient (``[source,lang]`` / ``[NOTE]``)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
|
|
19
|
+
from outliner.types import OutlineItem
|
|
20
|
+
from outliner.parsers.util import extract_summary
|
|
21
|
+
|
|
22
|
+
SYNTAX = "asciidoc"
|
|
23
|
+
EXTENSIONS = (".adoc", ".asciidoc")
|
|
24
|
+
|
|
25
|
+
_HEADING_RE = re.compile(r"^(={1,6})\s+(.+?)\s*$")
|
|
26
|
+
_ATTR_ENTRY_RE = re.compile(r"^:!?[A-Za-z0-9_-]+:(?:\s|$)")
|
|
27
|
+
_BLOCK_MACRO_RE = re.compile(r"^\[(?:source|NOTE|TIP|WARNING|CAUTION|IMPORTANT|listing|example|quote|verse|sidebar|pass|abstract|partintro)[,\]]")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def detect(lines: list[str]) -> bool:
|
|
31
|
+
"""Return True when content has unambiguous AsciiDoc markers.
|
|
32
|
+
|
|
33
|
+
We require co-occurring signals to avoid false-positives:
|
|
34
|
+
- A ``= Document Title`` line (level-0 heading) plus at least one
|
|
35
|
+
attribute entry or block macro; OR
|
|
36
|
+
- A block macro (``[source,…]``, admonition) alone.
|
|
37
|
+
"""
|
|
38
|
+
has_doc_title = False
|
|
39
|
+
has_section = False
|
|
40
|
+
has_attr = False
|
|
41
|
+
has_block = False
|
|
42
|
+
for line in lines:
|
|
43
|
+
s = line.rstrip()
|
|
44
|
+
if _BLOCK_MACRO_RE.match(s):
|
|
45
|
+
has_block = True
|
|
46
|
+
if _ATTR_ENTRY_RE.match(s):
|
|
47
|
+
has_attr = True
|
|
48
|
+
m = _HEADING_RE.match(s)
|
|
49
|
+
if m:
|
|
50
|
+
if len(m.group(1)) == 1:
|
|
51
|
+
has_doc_title = True
|
|
52
|
+
else:
|
|
53
|
+
has_section = True
|
|
54
|
+
if has_block:
|
|
55
|
+
return True
|
|
56
|
+
# Level-0 document title paired with attribute entries or section headings
|
|
57
|
+
if has_doc_title and (has_attr or has_section):
|
|
58
|
+
return True
|
|
59
|
+
return False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def parse(text: str) -> Iterator[OutlineItem]:
|
|
63
|
+
lines = text.splitlines(keepends=True)
|
|
64
|
+
n = len(lines)
|
|
65
|
+
|
|
66
|
+
headings: list[tuple[int, int, str]] = [] # (0-based idx, level, sig)
|
|
67
|
+
|
|
68
|
+
for i, line in enumerate(lines):
|
|
69
|
+
stripped = line.rstrip("\r\n")
|
|
70
|
+
m = _HEADING_RE.match(stripped)
|
|
71
|
+
if m:
|
|
72
|
+
level = len(m.group(1))
|
|
73
|
+
sig = "=" * level + " " + m.group(2)
|
|
74
|
+
headings.append((i, level, sig))
|
|
75
|
+
|
|
76
|
+
if not headings:
|
|
77
|
+
# Fallback: first non-empty line spans the whole file
|
|
78
|
+
first_sig = next((l.strip() for l in lines if l.strip()), "")
|
|
79
|
+
if first_sig:
|
|
80
|
+
yield OutlineItem(start=1, count=n, signature=extract_summary(first_sig))
|
|
81
|
+
return
|
|
82
|
+
|
|
83
|
+
for idx, (line_idx, level, sig) in enumerate(headings):
|
|
84
|
+
end_line = n
|
|
85
|
+
for future_line_idx, future_level, _ in headings[idx + 1:]:
|
|
86
|
+
if future_level <= level:
|
|
87
|
+
end_line = future_line_idx
|
|
88
|
+
break
|
|
89
|
+
yield OutlineItem(start=line_idx + 1, count=end_line - line_idx, signature=sig)
|
outliner/parsers/c.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""C/C++ outline parser (regex-based)."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections.abc import Iterator
|
|
5
|
+
|
|
6
|
+
from outliner.types import OutlineItem
|
|
7
|
+
from outliner.parsers.util import extract_signature, indent_level, seek_comment_start, seek_brace_end
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _block_comment_set(lines: list[str]) -> set[int]:
|
|
11
|
+
"""Return 0-based line indices that are inside a /* */ block comment.
|
|
12
|
+
|
|
13
|
+
The opening line (containing /*) is NOT included unless it is also
|
|
14
|
+
a continuation (i.e. the same line also contains text after the /*)
|
|
15
|
+
that carries no code — callers skip it based on the leading * check.
|
|
16
|
+
Subsequent lines until the matching */ are included.
|
|
17
|
+
"""
|
|
18
|
+
inside = False
|
|
19
|
+
result: set[int] = set()
|
|
20
|
+
for i, raw in enumerate(lines):
|
|
21
|
+
if inside:
|
|
22
|
+
result.add(i)
|
|
23
|
+
if "*/" in raw:
|
|
24
|
+
inside = False
|
|
25
|
+
elif "/*" in raw:
|
|
26
|
+
pos = raw.index("/*")
|
|
27
|
+
if raw.find("*/", pos + 2) == -1:
|
|
28
|
+
inside = True # comment continues beyond this line
|
|
29
|
+
return result
|
|
30
|
+
|
|
31
|
+
SYNTAX = "c"
|
|
32
|
+
EXTENSIONS = (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp", ".hxx", ".hh")
|
|
33
|
+
|
|
34
|
+
# ---------------------------------------------------------------------------
|
|
35
|
+
# Detection
|
|
36
|
+
# ---------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
_INCLUDE_RE = re.compile(r"^\s*#\s*include\s*[<\"]")
|
|
39
|
+
_DETECT_STRUCT_RE = re.compile(r"\b(?:struct|class|namespace|union|enum)\s+\w+")
|
|
40
|
+
_DETECT_FUNC_RE = re.compile(r"\w+\s*\([^)\n]*\)\s*(?:const\s+)?[{;]")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def detect(lines: list[str]) -> bool:
|
|
44
|
+
"""Detect C/C++: requires #include AND a structural code marker."""
|
|
45
|
+
if not any(_INCLUDE_RE.match(l) for l in lines):
|
|
46
|
+
return False
|
|
47
|
+
text = "\n".join(lines)
|
|
48
|
+
return bool(_DETECT_STRUCT_RE.search(text) or _DETECT_FUNC_RE.search(text))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
# Macro (#define)
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
_DEFINE_RE = re.compile(r"^\s*#\s*define\s+\w+")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _collect_define(lines: list[str], start: int) -> tuple[str, int]:
|
|
59
|
+
"""Collect a #define, following backslash line continuations."""
|
|
60
|
+
parts = [lines[start].rstrip()]
|
|
61
|
+
i = start
|
|
62
|
+
while parts[-1].endswith("\\") and i + 1 < len(lines):
|
|
63
|
+
i += 1
|
|
64
|
+
parts.append(lines[i].rstrip())
|
|
65
|
+
sig = " ".join(p.rstrip("\\").strip() for p in parts)
|
|
66
|
+
sig = re.sub(r"\s+", " ", sig).strip()
|
|
67
|
+
return sig, i
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# ---------------------------------------------------------------------------
|
|
71
|
+
# Template prefix
|
|
72
|
+
# ---------------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
_TEMPLATE_RE = re.compile(r"^\s*template\s*<")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _collect_template_sig(lines: list[str], start: int) -> tuple[str, int]:
|
|
78
|
+
"""Collect template<...> parameters, handling nested angle brackets."""
|
|
79
|
+
depth = 0
|
|
80
|
+
parts: list[str] = []
|
|
81
|
+
for i in range(start, min(start + 10, len(lines))):
|
|
82
|
+
raw = lines[i]
|
|
83
|
+
for ch in raw:
|
|
84
|
+
if ch == "<":
|
|
85
|
+
depth += 1
|
|
86
|
+
elif ch == ">":
|
|
87
|
+
depth -= 1
|
|
88
|
+
parts.append(raw.strip())
|
|
89
|
+
if depth <= 0:
|
|
90
|
+
break
|
|
91
|
+
return extract_signature(parts), i
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------------------
|
|
95
|
+
# Type declarations (struct / class / union / enum / namespace)
|
|
96
|
+
# ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
# Matches 'struct Name', 'class Name', etc. but NOT 'struct Name varname'
|
|
99
|
+
# Lookahead ensures after the name there is no other identifier (variable name).
|
|
100
|
+
_TYPE_RE = re.compile(
|
|
101
|
+
r"^\s*"
|
|
102
|
+
r"(?:(?:static|inline|extern|virtual|explicit|constexpr|friend)\s+)*"
|
|
103
|
+
r"(?:typedef\s+)?"
|
|
104
|
+
r"(?:struct|class|union|enum(?:\s+class)?|namespace)\s+\w+"
|
|
105
|
+
r"\s*(?=[{;:<]|//|$)" # followed by {, ;, :, <, //, or end-of-line
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# ---------------------------------------------------------------------------
|
|
109
|
+
# Function / method detection
|
|
110
|
+
# ---------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
_FLOW_STARTERS = frozenset({
|
|
113
|
+
"if", "else", "while", "for", "do", "switch", "case",
|
|
114
|
+
"return", "goto", "throw", "try", "catch",
|
|
115
|
+
"sizeof", "typeof", "alignof", "decltype",
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
_STMT_START_RE = re.compile(
|
|
119
|
+
r"^\s*(?:return|throw|break|continue|goto|delete\b|assert\b|static_assert\b)\b"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
# Identifier (with optional ~) or operator overload, followed by (
|
|
123
|
+
_FUNC_NAME_PAREN_RE = re.compile(
|
|
124
|
+
r"(~?\w+|operator\s*(?:\(\)|[+\-*/%^&|~!<>=,\[\]()\s]+?))\s*\("
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _is_func_line(raw: str) -> bool:
|
|
129
|
+
"""Return True if line looks like a C/C++ function/method declaration."""
|
|
130
|
+
s = raw.strip()
|
|
131
|
+
# Skip comment lines, constructor-init-list and comma continuations
|
|
132
|
+
if not s or s[0] in ("*", ":", ",") or s.startswith("//") or s.startswith("/*"):
|
|
133
|
+
return False
|
|
134
|
+
if _STMT_START_RE.match(raw):
|
|
135
|
+
return False
|
|
136
|
+
for m in _FUNC_NAME_PAREN_RE.finditer(raw):
|
|
137
|
+
name = m.group(1).strip()
|
|
138
|
+
if name in _FLOW_STARTERS:
|
|
139
|
+
continue
|
|
140
|
+
prefix = raw[: m.start()].strip()
|
|
141
|
+
if not prefix:
|
|
142
|
+
continue # no return type — bare call or constructor without qualifier
|
|
143
|
+
# Exclude: assignment (x = func(...)) and member access (p->func(...))
|
|
144
|
+
if "=" in prefix or "->" in prefix:
|
|
145
|
+
continue
|
|
146
|
+
# Exclude: prefix contains a comment → tail of a statement line
|
|
147
|
+
if "//" in prefix:
|
|
148
|
+
continue
|
|
149
|
+
# Exclude: nested call — prefix has unmatched open paren
|
|
150
|
+
if prefix.count("(") > prefix.count(")"):
|
|
151
|
+
continue
|
|
152
|
+
# Exclude: bare namespace/template qualifier with no return type (e.g. "std::", "Foo<T>::")
|
|
153
|
+
if prefix.endswith("::") and " " not in prefix:
|
|
154
|
+
continue
|
|
155
|
+
# Exclude: member access via . or closing bracket
|
|
156
|
+
if re.search(r"[).\]]\s*$", prefix):
|
|
157
|
+
continue
|
|
158
|
+
first_word = re.split(r"\W+", prefix.lstrip())[0] if prefix.lstrip() else ""
|
|
159
|
+
if first_word in _FLOW_STARTERS:
|
|
160
|
+
continue
|
|
161
|
+
return True
|
|
162
|
+
return False
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
# ---------------------------------------------------------------------------
|
|
166
|
+
# Signature collection
|
|
167
|
+
# ---------------------------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _collect_sig(lines: list[str], start: int) -> tuple[str, int, bool]:
|
|
171
|
+
"""Collect a C/C++ function or type signature spanning multiple lines.
|
|
172
|
+
|
|
173
|
+
Tracks parenthesis depth; stops when depth returns to 0 and line ends with
|
|
174
|
+
{ (has body) or ; (declaration only).
|
|
175
|
+
Returns (signature, last_sig_line_0based, has_body).
|
|
176
|
+
"""
|
|
177
|
+
depth = 0
|
|
178
|
+
parts: list[str] = []
|
|
179
|
+
ind = " " * indent_level(lines[start])
|
|
180
|
+
has_body = False
|
|
181
|
+
|
|
182
|
+
for i in range(start, min(start + 30, len(lines))):
|
|
183
|
+
raw = lines[i]
|
|
184
|
+
for ch in raw:
|
|
185
|
+
if ch == "(":
|
|
186
|
+
depth += 1
|
|
187
|
+
elif ch == ")":
|
|
188
|
+
depth -= 1
|
|
189
|
+
parts.append(raw.strip())
|
|
190
|
+
if depth <= 0:
|
|
191
|
+
bd = raw.count("{") - raw.count("}")
|
|
192
|
+
if bd > 0 or (bd == 0 and raw.rstrip().endswith("}")):
|
|
193
|
+
has_body = True
|
|
194
|
+
break
|
|
195
|
+
if raw.rstrip().endswith(";"):
|
|
196
|
+
break
|
|
197
|
+
|
|
198
|
+
sig = ind + extract_signature(parts, strip="{;")
|
|
199
|
+
# For one-liner bodies the inline body may remain; truncate at first {
|
|
200
|
+
if has_body:
|
|
201
|
+
brace = sig.find("{")
|
|
202
|
+
if brace != -1:
|
|
203
|
+
sig = sig[:brace].rstrip()
|
|
204
|
+
# Strip constructor init list: ): ... before end of sig
|
|
205
|
+
sig = re.sub(r"\)\s*:(?!:)[^{;]*$", ")", sig).rstrip()
|
|
206
|
+
return sig, i, has_body
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def parse(text: str) -> Iterator[OutlineItem]:
|
|
210
|
+
_is_comment = lambda _, s: s[:1] in '/*'
|
|
211
|
+
lines = text.splitlines()
|
|
212
|
+
n = len(lines)
|
|
213
|
+
block_comments = _block_comment_set(lines)
|
|
214
|
+
i = 0
|
|
215
|
+
|
|
216
|
+
while i < n:
|
|
217
|
+
line = lines[i]
|
|
218
|
+
|
|
219
|
+
# Skip lines inside /* */ block comments, blank lines, and line comments
|
|
220
|
+
s = line.strip()
|
|
221
|
+
if i in block_comments or not s or s[0] == "*" or s.startswith("//"):
|
|
222
|
+
i += 1
|
|
223
|
+
continue
|
|
224
|
+
|
|
225
|
+
# --- #define macros ---
|
|
226
|
+
if _DEFINE_RE.match(line):
|
|
227
|
+
sig, sig_end = _collect_define(lines, i)
|
|
228
|
+
start = seek_comment_start(lines, i, _is_comment)
|
|
229
|
+
yield OutlineItem(start=start + 1, count=sig_end - start + 1, signature=sig)
|
|
230
|
+
i = sig_end + 1
|
|
231
|
+
continue
|
|
232
|
+
|
|
233
|
+
# Skip other preprocessor directives (#if, #ifdef, #include, #pragma, etc.)
|
|
234
|
+
if s.startswith("#"):
|
|
235
|
+
i += 1
|
|
236
|
+
continue
|
|
237
|
+
|
|
238
|
+
# --- template<...> + following declaration ---
|
|
239
|
+
if _TEMPLATE_RE.match(line):
|
|
240
|
+
tmpl_sig, tmpl_end = _collect_template_sig(lines, i)
|
|
241
|
+
start = seek_comment_start(lines, i, _is_comment)
|
|
242
|
+
# Find the declaration following the template params (skip blanks and preprocessor)
|
|
243
|
+
j = tmpl_end + 1
|
|
244
|
+
while j < n and (not lines[j].strip() or lines[j].strip().startswith("#")):
|
|
245
|
+
j += 1
|
|
246
|
+
if j < n and (_TYPE_RE.match(lines[j]) or _is_func_line(lines[j])):
|
|
247
|
+
is_type_decl = bool(_TYPE_RE.match(lines[j]))
|
|
248
|
+
decl_sig, decl_end, has_body = _collect_sig(lines, j)
|
|
249
|
+
full_sig = tmpl_sig + " " + decl_sig.strip()
|
|
250
|
+
end = seek_brace_end(lines, decl_end) if has_body else decl_end + 1
|
|
251
|
+
yield OutlineItem(start=start + 1, count=end - start, signature=full_sig)
|
|
252
|
+
if has_body and not is_type_decl:
|
|
253
|
+
i = end # skip function body entirely
|
|
254
|
+
else:
|
|
255
|
+
i = decl_end + 1 # advance into type body so members are parsed
|
|
256
|
+
else:
|
|
257
|
+
i = tmpl_end + 1
|
|
258
|
+
continue
|
|
259
|
+
|
|
260
|
+
# --- type declarations (struct/class/union/enum/namespace) ---
|
|
261
|
+
if _TYPE_RE.match(line):
|
|
262
|
+
sig, sig_end, has_body = _collect_sig(lines, i)
|
|
263
|
+
start = seek_comment_start(lines, i, _is_comment)
|
|
264
|
+
end = seek_brace_end(lines, sig_end) if has_body else sig_end + 1
|
|
265
|
+
yield OutlineItem(start=start + 1, count=end - start, signature=sig)
|
|
266
|
+
i = sig_end + 1 # advance into body to parse members
|
|
267
|
+
continue
|
|
268
|
+
|
|
269
|
+
# --- function / method declarations and definitions ---
|
|
270
|
+
if _is_func_line(line):
|
|
271
|
+
sig, sig_end, has_body = _collect_sig(lines, i)
|
|
272
|
+
start = seek_comment_start(lines, i, _is_comment)
|
|
273
|
+
end = seek_brace_end(lines, sig_end) if has_body else sig_end + 1
|
|
274
|
+
yield OutlineItem(start=start + 1, count=end - start, signature=sig)
|
|
275
|
+
if has_body:
|
|
276
|
+
i = end # skip body to avoid matching statements inside
|
|
277
|
+
else:
|
|
278
|
+
i = sig_end + 1
|
|
279
|
+
continue
|
|
280
|
+
|
|
281
|
+
i += 1
|