featuregraph-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.
@@ -0,0 +1,264 @@
1
+ """Lexical masking shared by annotate, parsers, and dependency inference.
2
+
3
+ Matching tags or identifiers against raw text lets a template literal or a
4
+ comment forge them. Every consumer works from one of two same-length views:
5
+
6
+ code_only(text, lang) comments and strings blanked
7
+ comment_only(text, lang) only comments kept
8
+
9
+ Newlines are preserved in both, so line numbers never shift.
10
+
11
+ ponytail: template literals are masked wholesale, including ${...}
12
+ interpolations. Add interpolation-aware lexing if a consumer ever needs
13
+ tags inside templates.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ CODE = 0
19
+ STRING = 1
20
+ COMMENT = 2
21
+
22
+ _REGEX_KEYWORDS = {
23
+ "return", "typeof", "case", "in", "of", "yield", "await", "void",
24
+ "delete", "do", "else", "instanceof",
25
+ }
26
+
27
+ _SUFFIX_LANG = {
28
+ ".py": "python",
29
+ ".ts": "js", ".tsx": "js", ".js": "js", ".jsx": "js",
30
+ ".go": "go", ".rs": "rust",
31
+ ".java": "java", ".kt": "kotlin", ".kts": "kotlin",
32
+ ".cs": "csharp",
33
+ ".c": "c", ".h": "c", ".cpp": "cpp", ".cc": "cpp", ".cxx": "cpp", ".hpp": "cpp",
34
+ ".php": "php", ".rb": "ruby",
35
+ ".swift": "swift", ".dart": "dart",
36
+ ".sh": "shell", ".bash": "shell", ".zsh": "shell",
37
+ }
38
+
39
+
40
+ def lang_for_suffix(suffix: str) -> str:
41
+ return _SUFFIX_LANG.get(suffix.lower(), "other")
42
+
43
+
44
+ def _flags(lang: str) -> dict:
45
+ lang = (lang or "").lower()
46
+ if lang == "python":
47
+ return {"hash": True, "slash": False, "block": False, "triple": True,
48
+ "templates": False, "interp": False, "regex": False, "escapes": True,
49
+ "tmpl_escapes": True}
50
+ if lang in ("ruby", "shell"):
51
+ return {"hash": True, "slash": False, "block": False, "triple": False,
52
+ "templates": False, "interp": False, "regex": False, "escapes": True,
53
+ "tmpl_escapes": True}
54
+ if lang == "php":
55
+ return {"hash": True, "slash": True, "block": True, "triple": False,
56
+ "templates": False, "interp": False, "regex": False, "escapes": True,
57
+ "tmpl_escapes": True}
58
+ # C-family (and the generic fallback): //, /* */, '...', "..."
59
+ # Go double-quoted strings honour backslash escapes; only backtick raw strings do not.
60
+ return {"hash": False, "slash": True, "block": True, "triple": False,
61
+ "templates": lang in ("js", "ts", "go"),
62
+ "interp": lang in ("js", "ts"),
63
+ "regex": lang in ("js", "ts"),
64
+ "escapes": True,
65
+ "tmpl_escapes": lang != "go"}
66
+
67
+
68
+ def _regex_allowed(source: str, i: int) -> bool:
69
+ """JS/TS regex literals start after an operator, delimiter, keyword, or line start."""
70
+ j = i - 1
71
+ while j >= 0 and source[j] in " \t":
72
+ j -= 1
73
+ if j < 0 or source[j] in "\r\n":
74
+ return True
75
+ if source[j] in "([{,;:=!&|?}":
76
+ return True
77
+ if source[j] == ">" and j > 0 and source[j - 1] == "=":
78
+ return True
79
+ k = j
80
+ while k >= 0 and (source[k].isalnum() or source[k] in "_$"):
81
+ k -= 1
82
+ return source[k + 1 : j + 1] in _REGEX_KEYWORDS
83
+
84
+
85
+ # ponytail: ASI-sensitive `foo` newline `/re/` and `) /re/` still read as division;
86
+ # a real tokenizer is the upgrade if either ever matters.
87
+
88
+
89
+ def _rust_char_literal(source: str, i: int) -> bool:
90
+ """True when the quote at *i* opens a Rust char literal, not a lifetime."""
91
+ n = len(source)
92
+ if i + 2 < n and source[i + 1] not in ("'", "\\", "\r", "\n") and source[i + 2] == "'":
93
+ return True
94
+ if i + 2 < n and source[i + 1] == "\\":
95
+ for j in range(i + 2, min(n, i + 12)):
96
+ if source[j] in "\r\n":
97
+ return False
98
+ if source[j] == "'":
99
+ return True
100
+ return False
101
+
102
+
103
+ # @feature [LEXMASK-01] Classify source characters
104
+ def classify(source: str, lang: str = "other") -> bytearray:
105
+ """Per-character classes: CODE, STRING or COMMENT (same length as source)."""
106
+ lang = (lang or "").lower()
107
+ flags = _flags(lang)
108
+ cls = bytearray(len(source))
109
+ stack = [["code"]]
110
+ i, n = 0, len(source)
111
+
112
+ while i < n:
113
+ ctx = stack[-1]
114
+ kind = ctx[0]
115
+ ch = source[i]
116
+
117
+ if kind == "line":
118
+ if ch == "\n":
119
+ stack.pop()
120
+ else:
121
+ cls[i] = COMMENT
122
+ i += 1
123
+ continue
124
+
125
+ if kind == "block":
126
+ cls[i] = COMMENT
127
+ if ch == "*" and i + 1 < n and source[i + 1] == "/":
128
+ cls[i + 1] = COMMENT
129
+ stack.pop()
130
+ i += 2
131
+ else:
132
+ i += 1
133
+ continue
134
+
135
+ if kind == "str":
136
+ cls[i] = STRING
137
+ if ch == "\\" and flags["escapes"] and i + 1 < n:
138
+ cls[i + 1] = STRING
139
+ i += 2
140
+ else:
141
+ if ch == ctx[1]:
142
+ stack.pop()
143
+ i += 1
144
+ continue
145
+
146
+ if kind == "regex":
147
+ cls[i] = STRING
148
+ if ch == "\\" and i + 1 < n:
149
+ cls[i + 1] = STRING
150
+ i += 2
151
+ elif ch in "\r\n":
152
+ stack.pop() # unterminated regex: fall back to code on the next line
153
+ elif ch == "[":
154
+ ctx[1] = 1
155
+ i += 1
156
+ elif ch == "]" and ctx[1]:
157
+ ctx[1] = 0
158
+ i += 1
159
+ elif ch == "/" and not ctx[1]:
160
+ stack.pop()
161
+ i += 1
162
+ else:
163
+ i += 1
164
+ continue
165
+
166
+ if kind == "triple":
167
+ quote = ctx[1]
168
+ if source.startswith(quote * 3, i):
169
+ cls[i] = cls[i + 1] = cls[i + 2] = STRING
170
+ stack.pop()
171
+ i += 3
172
+ elif ch == "\\" and i + 1 < n:
173
+ cls[i] = cls[i + 1] = STRING
174
+ i += 2
175
+ else:
176
+ cls[i] = STRING
177
+ i += 1
178
+ continue
179
+
180
+ if kind == "tmpl":
181
+ cls[i] = STRING
182
+ if ch == "\\" and flags["tmpl_escapes"] and i + 1 < n:
183
+ cls[i + 1] = STRING
184
+ i += 2
185
+ elif ch == "`":
186
+ stack.pop()
187
+ i += 1
188
+ elif flags["interp"] and ch == "$" and i + 1 < n and source[i + 1] == "{":
189
+ cls[i + 1] = STRING
190
+ stack.append(["interp", 1])
191
+ i += 2
192
+ else:
193
+ i += 1
194
+ continue
195
+
196
+ # code (top level or inside ${...}) — transitions first
197
+ # PHP: #[...] is an attribute, not a hash comment.
198
+ if flags["hash"] and ch == "#" and not (
199
+ lang == "php" and i + 1 < n and source[i + 1] == "["
200
+ ):
201
+ cls[i] = COMMENT
202
+ stack.append(["line"])
203
+ i += 1
204
+ continue
205
+ if flags["slash"] and ch == "/" and i + 1 < n and source[i + 1] == "/":
206
+ cls[i] = cls[i + 1] = COMMENT
207
+ stack.append(["line"])
208
+ i += 2
209
+ continue
210
+ if flags["block"] and ch == "/" and i + 1 < n and source[i + 1] == "*":
211
+ cls[i] = cls[i + 1] = COMMENT
212
+ stack.append(["block"])
213
+ i += 2
214
+ continue
215
+ if flags["regex"] and ch == "/" and _regex_allowed(source, i):
216
+ cls[i] = STRING
217
+ stack.append(["regex", 0])
218
+ i += 1
219
+ continue
220
+ if ch == "'" or ch == '"':
221
+ if lang == "rust" and ch == "'" and not _rust_char_literal(source, i):
222
+ i += 1 # lifetime or label, never a char literal
223
+ continue
224
+ if flags["triple"] and source.startswith(ch * 3, i):
225
+ cls[i] = cls[i + 1] = cls[i + 2] = STRING
226
+ stack.append(["triple", ch])
227
+ i += 3
228
+ else:
229
+ cls[i] = STRING
230
+ stack.append(["str", ch])
231
+ i += 1
232
+ continue
233
+ if flags["templates"] and ch == "`":
234
+ cls[i] = STRING
235
+ stack.append(["tmpl"])
236
+ i += 1
237
+ continue
238
+
239
+ if kind == "interp":
240
+ cls[i] = STRING
241
+ if ch == "{":
242
+ ctx[1] += 1
243
+ elif ch == "}":
244
+ ctx[1] -= 1
245
+ if ctx[1] == 0:
246
+ stack.pop()
247
+ i += 1
248
+
249
+ return cls
250
+
251
+
252
+ def _view(source: str, cls: bytearray, wanted: int) -> str:
253
+ return "".join(
254
+ ch if (kind == wanted or ch in "\r\n") else " "
255
+ for ch, kind in zip(source, cls, strict=False)
256
+ )
257
+
258
+
259
+ def code_only(source: str, lang: str = "other") -> str:
260
+ return _view(source, classify(source, lang), CODE)
261
+
262
+
263
+ def comment_only(source: str, lang: str = "other") -> str:
264
+ return _view(source, classify(source, lang), COMMENT)
@@ -0,0 +1,233 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from . import lexmask
8
+ from .tags import (
9
+ DEPENDS_TAG_REGEX,
10
+ FEATURE_TAG_REGEX,
11
+ extract_contract_tags,
12
+ )
13
+
14
+ # Tags are only honoured on comment lines; the comment mask rejects string/template text
15
+ COMMENT_LINE_REGEX = re.compile(r"^\s*(?://|/\*|\*|#)")
16
+
17
+ # Declarations for symbol extraction
18
+ C_STYLE_DECL_REGEX = re.compile(
19
+ r"(?:(?:public|private|protected|static|async|fn|func|function|def|class|struct|interface|impl|enum|type)\s+)+([A-Za-z0-9_]+)",
20
+ re.IGNORECASE
21
+ )
22
+
23
+ # Go receiver methods: func (s *Server) Handle(...) -> Handle
24
+ GO_RECEIVER_REGEX = re.compile(r"^\s*func\s+\([^)]*\)\s*([A-Za-z0-9_]+)")
25
+
26
+ # Route patterns across frameworks
27
+ GENERIC_ROUTE_REGEX = re.compile(
28
+ r"(?:@(?:Get|Post|Put|Delete|Patch|Request)Mapping|"
29
+ r"\[(?:Http|Route)[A-Za-z0-9_\(\)\"\s/]+\]|"
30
+ r"#\[(?:get|post|put|delete|patch|route)\(|"
31
+ r"(?:Route|router|r|e|http)\.(?:get|post|put|delete|patch|HandleFunc|Handle)\(|"
32
+ r"(?:get|post|put|delete|patch)\s+['\"]/)",
33
+ re.IGNORECASE
34
+ )
35
+
36
+ SUPPORTED_EXTENSIONS = {
37
+ # Go
38
+ ".go": "go",
39
+ # Rust
40
+ ".rs": "rust",
41
+ # Java / Kotlin
42
+ ".java": "java",
43
+ ".kt": "kotlin",
44
+ ".kts": "kotlin",
45
+ # C# / .NET
46
+ ".cs": "csharp",
47
+ # C / C++
48
+ ".c": "c",
49
+ ".cpp": "cpp",
50
+ ".cc": "cpp",
51
+ ".cxx": "cpp",
52
+ ".h": "c_header",
53
+ ".hpp": "cpp_header",
54
+ # PHP
55
+ ".php": "php",
56
+ # Ruby
57
+ ".rb": "ruby",
58
+ # Swift / Dart
59
+ ".swift": "swift",
60
+ ".dart": "dart",
61
+ # Shell
62
+ ".sh": "shell",
63
+ ".bash": "shell",
64
+ ".zsh": "shell",
65
+ }
66
+
67
+
68
+ # @feature [PARSER_GENERIC-01] Generic Feature Parser
69
+ class GenericFeatureParser:
70
+ """Universal parser for Go, Rust, Java, C#, C/C++, PHP, Ruby, Swift, Dart, and Shell."""
71
+
72
+ @staticmethod
73
+ def is_supported(file_path: Path) -> bool:
74
+ return file_path.suffix.lower() in SUPPORTED_EXTENSIONS
75
+
76
+ @staticmethod
77
+ def _decl_match(code_line: str):
78
+ """Go receiver methods first, then the generic C-family declaration pattern."""
79
+ return GO_RECEIVER_REGEX.search(code_line) or C_STYLE_DECL_REGEX.search(code_line)
80
+
81
+ @staticmethod
82
+ def parse_file(file_path: Path) -> list[dict[str, Any]]:
83
+ if not file_path.exists() or not file_path.is_file():
84
+ return []
85
+
86
+ results: list[dict[str, Any]] = []
87
+ try:
88
+ content = file_path.read_text(encoding="utf-8", errors="replace")
89
+ lines = content.splitlines()
90
+ except (UnicodeDecodeError, OSError):
91
+ return []
92
+
93
+ ext = file_path.suffix.lower()
94
+ lang = SUPPORTED_EXTENSIONS.get(ext, "generic")
95
+ code_lines = lexmask.code_only(content, lang).splitlines()
96
+ comment_lines = lexmask.comment_only(content, lang).splitlines()
97
+ cls = lexmask.classify(content, lang)
98
+ starts = [0]
99
+ for raw_line in content.splitlines(keepends=True):
100
+ starts.append(starts[-1] + len(raw_line))
101
+
102
+ for idx, line in enumerate(lines, 1):
103
+ feat_match = (
104
+ FEATURE_TAG_REGEX.search(comment_lines[idx - 1])
105
+ if COMMENT_LINE_REGEX.match(line)
106
+ else None
107
+ )
108
+ if not feat_match:
109
+ # Also check for web framework route annotations/decorators
110
+ route_match = GENERIC_ROUTE_REGEX.search(line)
111
+ route_pos = starts[idx - 1] + route_match.start() if route_match else 0
112
+ if route_match and route_pos < len(cls) and cls[route_pos] == lexmask.CODE:
113
+ # Look forward 1-3 lines for function declaration
114
+ symbol_name = ""
115
+ start_line = idx
116
+ end_line = idx + 15
117
+ for forward_i in range(idx - 1, min(len(lines), idx + 3)):
118
+ decl_match = GenericFeatureParser._decl_match(code_lines[forward_i])
119
+ if decl_match:
120
+ symbol_name = decl_match.group(1)
121
+ start_line = forward_i + 1
122
+ end_line = GenericFeatureParser._find_block_end(
123
+ lines, forward_i, lang, code_lines
124
+ )
125
+ break
126
+ if symbol_name:
127
+ results.append({
128
+ "feature_id": f"ROUTE-{symbol_name.upper()}",
129
+ "name": f"API Endpoint `{symbol_name}` ({route_match.group(0)})",
130
+ "symbol": symbol_name,
131
+ "type": "endpoint",
132
+ "start_line": start_line,
133
+ "end_line": end_line,
134
+ "depends_on": [],
135
+ "file": str(file_path),
136
+ })
137
+ continue
138
+
139
+ feat_id = feat_match.group(1).upper()
140
+ desc = (feat_match.group(2) or "").strip() or f"{lang.capitalize()} Feature"
141
+
142
+ # Check surrounding lines for @depends
143
+ context_chunk = "\n".join(comment_lines[max(0, idx - 3): min(len(lines), idx + 3)])
144
+ dep_match = DEPENDS_TAG_REGEX.search(context_chunk)
145
+ deps = []
146
+ if dep_match:
147
+ deps = [d.strip().strip("[]") for d in dep_match.group(1).split(",") if d.strip()]
148
+ contract = extract_contract_tags(context_chunk)
149
+
150
+ # Look forward up to 6 lines to find symbol and block end
151
+ symbol_name = file_path.stem
152
+ symbol_type = "module"
153
+ start_line = idx
154
+ end_line = min(idx + 25, len(lines))
155
+
156
+ for forward_i in range(idx, min(len(lines), idx + 6)):
157
+ decl_match = GenericFeatureParser._decl_match(code_lines[forward_i])
158
+ if decl_match:
159
+ symbol_name = decl_match.group(1)
160
+ decl_line_str = code_lines[forward_i].lower()
161
+ if any(kw in decl_line_str for kw in ["class", "struct", "interface", "type", "impl"]):
162
+ symbol_type = "class"
163
+ else:
164
+ symbol_type = "function"
165
+ start_line = forward_i + 1
166
+ end_line = GenericFeatureParser._find_block_end(
167
+ lines, forward_i, lang, code_lines
168
+ )
169
+ break
170
+
171
+ results.append({
172
+ "feature_id": feat_id,
173
+ "name": desc,
174
+ "symbol": symbol_name,
175
+ "type": symbol_type,
176
+ "start_line": start_line,
177
+ "end_line": end_line,
178
+ "depends_on": deps,
179
+ "file": str(file_path),
180
+ **contract,
181
+ })
182
+
183
+ return results
184
+
185
+ @staticmethod
186
+ def _find_block_end(
187
+ lines: list[str], start_idx: int, lang: str, code_lines: list[str] | None = None
188
+ ) -> int:
189
+ """Finds the ending line number (1-indexed) of a block.
190
+
191
+ *code_lines* is the lexmask code-only view: strings and comments are blanked,
192
+ so braces inside them never affect depth.
193
+ """
194
+ total_lines = len(lines)
195
+ if start_idx >= total_lines:
196
+ return total_lines
197
+ scan = code_lines if code_lines is not None else lines
198
+
199
+ # Ruby block tracking (def/class/module ... end)
200
+ if lang == "ruby":
201
+ open_count = 0
202
+ found_start = False
203
+ for i in range(start_idx, total_lines):
204
+ line = scan[i].strip()
205
+ if not line:
206
+ continue
207
+ if re.match(r"^(?:def|class|module|if|unless|do)\b", line):
208
+ open_count += 1
209
+ found_start = True
210
+ if line == "end" or line.endswith(" end"):
211
+ open_count -= 1
212
+ if found_start and open_count <= 0:
213
+ return i + 1
214
+ return min(start_idx + 30, total_lines)
215
+
216
+ # Brace matching for C-family languages (Go, Rust, Java, C#, C/C++, PHP, Swift, Dart, Shell)
217
+ brace_count = 0
218
+ found_open = False
219
+
220
+ for i in range(start_idx, total_lines):
221
+ line = scan[i]
222
+ open_braces = line.count("{")
223
+ close_braces = line.count("}")
224
+
225
+ if open_braces > 0:
226
+ found_open = True
227
+
228
+ brace_count += open_braces - close_braces
229
+
230
+ if found_open and brace_count <= 0:
231
+ return i + 1
232
+
233
+ return min(start_idx + 30, total_lines)
@@ -0,0 +1,18 @@
1
+ """Structural contract shared by every language parser.
2
+
3
+ A parser is anything with a ``parse_file`` callable taking a ``Path`` and
4
+ returning a list of feature dicts. Keeping this as a Protocol (rather than a
5
+ base class) avoids forcing inheritance on parsers that are currently static
6
+ method collections.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Any, Protocol, runtime_checkable
13
+
14
+
15
+ @runtime_checkable
16
+ class FeatureParser(Protocol):
17
+ def parse_file(self, file_path: Path) -> list[dict[str, Any]]: # pragma: no cover - protocol
18
+ ...