margin-ai-code-detector 0.2.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.
- ai_code_detector/__init__.py +15 -0
- ai_code_detector/agent.py +56 -0
- ai_code_detector/aggregate.py +183 -0
- ai_code_detector/judge/__init__.py +1 -0
- ai_code_detector/judge/llm_judge.py +358 -0
- ai_code_detector/judge/prompts/__init__.py +1 -0
- ai_code_detector/judge/prompts/judge_v1.md +28 -0
- ai_code_detector/judge/prompts/judge_v2.md +28 -0
- ai_code_detector/judge/sampler.py +40 -0
- ai_code_detector/markers/__init__.py +108 -0
- ai_code_detector/markers/v1.toml +98 -0
- ai_code_detector/methodology/__init__.py +71 -0
- ai_code_detector/methodology/v0.toml +119 -0
- ai_code_detector/methodology/v1.toml +141 -0
- ai_code_detector/models.py +197 -0
- ai_code_detector/pipeline.py +457 -0
- ai_code_detector/py.typed +1 -0
- ai_code_detector/report.py +179 -0
- ai_code_detector/signals/__init__.py +7 -0
- ai_code_detector/signals/base.py +64 -0
- ai_code_detector/signals/file.py +277 -0
- ai_code_detector/signals/repo.py +183 -0
- ai_code_detector/source/__init__.py +95 -0
- ai_code_detector/source/javascript.py +227 -0
- ai_code_detector/source/python.py +129 -0
- margin_ai_code_detector-0.2.0.dist-info/METADATA +137 -0
- margin_ai_code_detector-0.2.0.dist-info/RECORD +30 -0
- margin_ai_code_detector-0.2.0.dist-info/WHEEL +4 -0
- margin_ai_code_detector-0.2.0.dist-info/entry_points.txt +2 -0
- margin_ai_code_detector-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Repository-level signals: commit history shape and README style."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from margin_core import Evidence
|
|
8
|
+
|
|
9
|
+
from ai_code_detector.models import SignalHit
|
|
10
|
+
from ai_code_detector.signals.base import RepoContext, RepoSignal, ramp
|
|
11
|
+
|
|
12
|
+
_CONVENTIONAL = re.compile(r"^[a-z]+(\([^)]*\))?!?: ", re.IGNORECASE)
|
|
13
|
+
_MESSY = re.compile(
|
|
14
|
+
r"\b(typo|oops|whoops|wip|tmp|temp|again|stuff|asdf|minor|forgot|small fix|quick fix|"
|
|
15
|
+
r"try|trying|maybe|hopefully|fixup|squash)\b|^revert\b|^merge\b",
|
|
16
|
+
re.IGNORECASE,
|
|
17
|
+
)
|
|
18
|
+
_EMOJI = re.compile("[\U0001f300-\U0001faff☀-➿]")
|
|
19
|
+
_TEMPLATE_SECTIONS = {
|
|
20
|
+
"features", "installation", "usage", "contributing", "license", "getting started",
|
|
21
|
+
"prerequisites", "project structure", "table of contents", "acknowledgments",
|
|
22
|
+
"acknowledgements", "roadmap", "tech stack", "configuration", "requirements",
|
|
23
|
+
} # fmt: skip
|
|
24
|
+
_MARKETING = re.compile(
|
|
25
|
+
r"\b(seamless(ly)?|powerful|robust|comprehensive|cutting-edge|effortless(ly)?|"
|
|
26
|
+
r"blazing(ly)?|leverag\w*|streamlin\w*|intuitive|elevate|empower\w*|delve|unlock|"
|
|
27
|
+
r"revolutioni[sz]\w*|state-of-the-art|game-chang\w*)\b",
|
|
28
|
+
re.IGNORECASE,
|
|
29
|
+
)
|
|
30
|
+
_README_NAMES = ("README.md", "README.rst", "README.txt", "README", "readme.md", "Readme.md")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CommitShape(RepoSignal):
|
|
34
|
+
"""A finished project arriving in one go, or many very large commits."""
|
|
35
|
+
|
|
36
|
+
id = "commit_shape"
|
|
37
|
+
version = "1"
|
|
38
|
+
family = "history"
|
|
39
|
+
|
|
40
|
+
def evaluate(self, ctx: RepoContext) -> list[SignalHit]:
|
|
41
|
+
if not ctx.commits:
|
|
42
|
+
return []
|
|
43
|
+
t = ctx.methodology.thresholds_for(self.id)
|
|
44
|
+
current = {f.path for f in ctx.workspace.files}
|
|
45
|
+
if len(current) < t["min_files"]:
|
|
46
|
+
return []
|
|
47
|
+
|
|
48
|
+
if len(ctx.commits) == 1:
|
|
49
|
+
sha = ctx.commits[0].sha
|
|
50
|
+
return [
|
|
51
|
+
self.hit(
|
|
52
|
+
t["single_commit_strength"],
|
|
53
|
+
"The whole project arrived in a single commit. AI-built projects often do, "
|
|
54
|
+
"but so do existing projects uploaded at once, so this is weak evidence.",
|
|
55
|
+
[Evidence(kind="commit", location=sha, detail="only commit")],
|
|
56
|
+
)
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
strength = 0.0
|
|
60
|
+
evidence: list[Evidence] = []
|
|
61
|
+
parts: list[str] = []
|
|
62
|
+
roots = [c for c in ctx.commits if not c.parents]
|
|
63
|
+
if roots and not ctx.history_truncated:
|
|
64
|
+
root = roots[-1]
|
|
65
|
+
share = len(set(ctx.changed_files.get(root.sha, [])) & current) / len(current)
|
|
66
|
+
if share >= t["first_share"]:
|
|
67
|
+
strength += 0.3 + 0.4 * ramp(share, t["first_share"], 1.0)
|
|
68
|
+
parts.append(f"the first commit already contained {share:.0%} of today's files")
|
|
69
|
+
evidence.append(
|
|
70
|
+
Evidence(kind="commit", location=root.sha, detail=f"first commit: {share:.0%}")
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
non_merge = [c for c in ctx.commits if len(c.parents) <= 1]
|
|
74
|
+
if len(non_merge) >= t["min_commits_for_large"]:
|
|
75
|
+
large = [
|
|
76
|
+
c
|
|
77
|
+
for c in non_merge
|
|
78
|
+
if len(ctx.changed_files.get(c.sha, [])) >= t["large_commit_files"]
|
|
79
|
+
]
|
|
80
|
+
share = len(large) / len(non_merge)
|
|
81
|
+
if share >= t["large_commit_share"]:
|
|
82
|
+
strength += 0.3
|
|
83
|
+
parts.append(
|
|
84
|
+
f"{share:.0%} of commits each touched {int(t['large_commit_files'])}+ files"
|
|
85
|
+
)
|
|
86
|
+
evidence += [
|
|
87
|
+
Evidence(
|
|
88
|
+
kind="commit",
|
|
89
|
+
location=c.sha,
|
|
90
|
+
detail=f"{len(ctx.changed_files.get(c.sha, []))} files: {c.subject[:60]}",
|
|
91
|
+
)
|
|
92
|
+
for c in large[:3]
|
|
93
|
+
]
|
|
94
|
+
if not parts:
|
|
95
|
+
return []
|
|
96
|
+
return [self.hit(strength, "History shape: " + "; ".join(parts) + ".", evidence)]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class HistoryDepth(RepoSignal):
|
|
100
|
+
"""A long, irregular history with small fixes and false starts suggests people at work."""
|
|
101
|
+
|
|
102
|
+
id = "history_depth"
|
|
103
|
+
version = "1"
|
|
104
|
+
family = "history"
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def _messy(subject: str) -> bool:
|
|
108
|
+
if _MESSY.search(subject):
|
|
109
|
+
return True
|
|
110
|
+
return not _CONVENTIONAL.match(subject) and len(subject.split()) <= 2
|
|
111
|
+
|
|
112
|
+
def evaluate(self, ctx: RepoContext) -> list[SignalHit]:
|
|
113
|
+
t = ctx.methodology.thresholds_for(self.id)
|
|
114
|
+
commits = ctx.commits
|
|
115
|
+
if len(commits) < t["small_min_commits"]:
|
|
116
|
+
return []
|
|
117
|
+
dates = [c.authored_at for c in commits]
|
|
118
|
+
span_days = (max(dates) - min(dates)).days
|
|
119
|
+
messy = [c for c in commits if self._messy(c.subject)]
|
|
120
|
+
share = len(messy) / len(commits)
|
|
121
|
+
if len(commits) >= t["min_commits"] and span_days >= t["min_span_days"]:
|
|
122
|
+
if share < t["messy_share"]:
|
|
123
|
+
return []
|
|
124
|
+
strength = -(0.3 + 0.4 * ramp(share, t["messy_share"], 0.5))
|
|
125
|
+
elif span_days >= t["small_min_span_days"] and share >= t["small_messy_share"]:
|
|
126
|
+
strength = -0.3
|
|
127
|
+
else:
|
|
128
|
+
return []
|
|
129
|
+
evidence = [
|
|
130
|
+
Evidence(kind="commit", location=c.sha, detail=f"'{c.subject[:60]}'") for c in messy[:3]
|
|
131
|
+
]
|
|
132
|
+
return [
|
|
133
|
+
self.hit(
|
|
134
|
+
strength,
|
|
135
|
+
f"{len(commits)} commits over {span_days} days, {share:.0%} of them small fixes, "
|
|
136
|
+
"reverts or terse messages: the irregular rhythm of people working.",
|
|
137
|
+
evidence,
|
|
138
|
+
)
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class ReadmePatterns(RepoSignal):
|
|
143
|
+
"""Emoji headings, a template section list and marketing words are common in AI READMEs."""
|
|
144
|
+
|
|
145
|
+
id = "readme_patterns"
|
|
146
|
+
version = "1"
|
|
147
|
+
family = "docs"
|
|
148
|
+
|
|
149
|
+
def evaluate(self, ctx: RepoContext) -> list[SignalHit]:
|
|
150
|
+
t = ctx.methodology.thresholds_for(self.id)
|
|
151
|
+
readme = next((n for n in _README_NAMES if ctx.workspace.get_file(n)), None)
|
|
152
|
+
if readme is None:
|
|
153
|
+
return []
|
|
154
|
+
text = ctx.workspace.read_text(readme, max_bytes=200_000)
|
|
155
|
+
headings = [line.lstrip("#").strip() for line in text.splitlines() if line.startswith("#")]
|
|
156
|
+
emoji = [h for h in headings if _EMOJI.search(h)]
|
|
157
|
+
plain = {_EMOJI.sub("", h).strip(" :").lower() for h in headings}
|
|
158
|
+
template = plain & _TEMPLATE_SECTIONS
|
|
159
|
+
marketing = {m.group(0).lower() for m in _MARKETING.finditer(text)}
|
|
160
|
+
|
|
161
|
+
strength = 0.0
|
|
162
|
+
parts: list[str] = []
|
|
163
|
+
if len(emoji) >= t["emoji_headings"]:
|
|
164
|
+
strength += 0.3
|
|
165
|
+
parts.append(f"{len(emoji)} headings start with emoji")
|
|
166
|
+
if len(template) >= t["template_sections"]:
|
|
167
|
+
strength += 0.2
|
|
168
|
+
parts.append(f"a template section list ({', '.join(sorted(template))})")
|
|
169
|
+
if len(marketing) >= t["marketing_words"]:
|
|
170
|
+
strength += 0.2
|
|
171
|
+
parts.append(f"marketing words ({', '.join(sorted(marketing)[:5])})")
|
|
172
|
+
if not parts:
|
|
173
|
+
return []
|
|
174
|
+
return [
|
|
175
|
+
self.hit(
|
|
176
|
+
min(t["max_strength"], strength),
|
|
177
|
+
"README style: " + "; ".join(parts) + ".",
|
|
178
|
+
[Evidence(kind="file", location=readme, detail="; ".join(parts))],
|
|
179
|
+
)
|
|
180
|
+
]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
REPO_SIGNALS: tuple[RepoSignal, ...] = (CommitShape(), HistoryDepth(), ReadmePatterns())
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Language-neutral facts about one source file, produced by a parser per language.
|
|
2
|
+
|
|
3
|
+
Signals read only :class:`SourceFile`, so adding a language means adding a parser here, not
|
|
4
|
+
changing signals. Language-specific judgements (what counts as a docstring, which comments
|
|
5
|
+
are commented-out code, which calls are leftover debugging) are made by the parser.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import PurePosixPath
|
|
14
|
+
|
|
15
|
+
_WORD_RE = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+")
|
|
16
|
+
DEBUG_WORDS = {"here", "debug", "test", "xxx", "ok", "hello", "asdf", "got here", "reached"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Comment:
|
|
21
|
+
line: int
|
|
22
|
+
text: str # without comment markers, stripped (block comments joined with spaces)
|
|
23
|
+
own_line: bool # True when nothing but whitespace precedes it
|
|
24
|
+
line_count: int = 1 # lines spanned (block comments)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Function:
|
|
29
|
+
name: str
|
|
30
|
+
line: int
|
|
31
|
+
end_line: int
|
|
32
|
+
statements: int # body statements, not counting a docstring
|
|
33
|
+
has_docstring: bool # Python docstring, or a JSDoc block directly above
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class SourceFile:
|
|
38
|
+
path: str
|
|
39
|
+
language: str
|
|
40
|
+
lines: list[str]
|
|
41
|
+
code_line_numbers: set[int]
|
|
42
|
+
comments: list[Comment]
|
|
43
|
+
docstring_lines: int
|
|
44
|
+
functions: list[Function]
|
|
45
|
+
identifiers: list[str]
|
|
46
|
+
quote_styles: Counter[str] = field(default_factory=Counter)
|
|
47
|
+
commented_code_lines: list[int] = field(default_factory=list)
|
|
48
|
+
debug_statements: list[tuple[int, str]] = field(default_factory=list)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def code_lines(self) -> int:
|
|
52
|
+
return len(self.code_line_numbers)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def own_line_comment_lines(self) -> int:
|
|
56
|
+
return sum(c.line_count for c in self.comments if c.own_line)
|
|
57
|
+
|
|
58
|
+
def next_code_line(self, after: int) -> int | None:
|
|
59
|
+
later = [n for n in self.code_line_numbers if n > after]
|
|
60
|
+
return min(later) if later else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def split_words(text: str) -> list[str]:
|
|
64
|
+
"""Lower-case words from prose or identifiers (``getUserName`` -> get, user, name)."""
|
|
65
|
+
words: list[str] = []
|
|
66
|
+
for chunk in re.split(r"[^A-Za-z0-9]+", text):
|
|
67
|
+
words += [w.lower() for w in _WORD_RE.findall(chunk)]
|
|
68
|
+
return words
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
PYTHON_SUFFIXES = {".py"}
|
|
72
|
+
JAVASCRIPT_SUFFIXES = {".js", ".jsx", ".mjs", ".cjs"}
|
|
73
|
+
TYPESCRIPT_SUFFIXES = {".ts", ".mts", ".cts", ".tsx"}
|
|
74
|
+
SUPPORTED_SUFFIXES = PYTHON_SUFFIXES | JAVASCRIPT_SUFFIXES | TYPESCRIPT_SUFFIXES
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def is_supported(path: str) -> bool:
|
|
78
|
+
lower = path.lower()
|
|
79
|
+
if lower.endswith((".d.ts", ".d.mts", ".d.cts")): # type declarations, not code
|
|
80
|
+
return False
|
|
81
|
+
return PurePosixPath(lower).suffix in SUPPORTED_SUFFIXES
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def parse_source(path: str, text: str) -> SourceFile | None:
|
|
85
|
+
"""Parse ``text`` with the parser for ``path``'s language; ``None`` if it cannot."""
|
|
86
|
+
suffix = PurePosixPath(path.lower()).suffix
|
|
87
|
+
if suffix in PYTHON_SUFFIXES:
|
|
88
|
+
from ai_code_detector.source.python import parse_python
|
|
89
|
+
|
|
90
|
+
return parse_python(path, text)
|
|
91
|
+
if suffix in JAVASCRIPT_SUFFIXES | TYPESCRIPT_SUFFIXES:
|
|
92
|
+
from ai_code_detector.source.javascript import parse_javascript
|
|
93
|
+
|
|
94
|
+
return parse_javascript(path, text)
|
|
95
|
+
return None
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""JavaScript and TypeScript parser, using tree-sitter.
|
|
2
|
+
|
|
3
|
+
``.js/.jsx/.mjs/.cjs`` use the JavaScript grammar (which includes JSX); ``.ts/.mts/.cts``
|
|
4
|
+
the TypeScript grammar and ``.tsx`` the TSX grammar. A JSDoc block (``/** ... */``) counts as
|
|
5
|
+
a docstring, and documents a function when it ends on the line just above it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from functools import cache
|
|
13
|
+
from pathlib import PurePosixPath
|
|
14
|
+
|
|
15
|
+
import tree_sitter_javascript
|
|
16
|
+
import tree_sitter_typescript
|
|
17
|
+
from tree_sitter import Language, Node, Parser
|
|
18
|
+
|
|
19
|
+
from ai_code_detector.source import DEBUG_WORDS, Comment, Function, SourceFile
|
|
20
|
+
|
|
21
|
+
MAX_ERROR_SHARE = 0.10 # more of the file than this inside ERROR nodes: treat as unparseable
|
|
22
|
+
_FUNCTIONS = {
|
|
23
|
+
"function_declaration", "function_expression", "arrow_function", "method_definition",
|
|
24
|
+
"generator_function_declaration", "generator_function",
|
|
25
|
+
} # fmt: skip
|
|
26
|
+
_DECLARATION_WRAPPERS = {
|
|
27
|
+
"lexical_declaration", "variable_declaration", "export_statement", "variable_declarator",
|
|
28
|
+
"pair", "public_field_definition", "assignment_expression", "expression_statement",
|
|
29
|
+
} # fmt: skip
|
|
30
|
+
_CODE_HINT = re.compile(
|
|
31
|
+
r"[(=;{\[]|\b(const|let|var|return|if|for|while|function|import|export|await)\b"
|
|
32
|
+
)
|
|
33
|
+
_CONSOLE = {"log", "debug", "info", "warn", "error", "trace"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@cache
|
|
37
|
+
def _parser(kind: str) -> Parser:
|
|
38
|
+
language = {
|
|
39
|
+
"javascript": lambda: tree_sitter_javascript.language(),
|
|
40
|
+
"typescript": lambda: tree_sitter_typescript.language_typescript(),
|
|
41
|
+
"tsx": lambda: tree_sitter_typescript.language_tsx(),
|
|
42
|
+
}[kind]()
|
|
43
|
+
return Parser(Language(language))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _grammar(path: str) -> str:
|
|
47
|
+
suffix = PurePosixPath(path.lower()).suffix
|
|
48
|
+
if suffix == ".tsx":
|
|
49
|
+
return "tsx"
|
|
50
|
+
if suffix in {".ts", ".mts", ".cts"}:
|
|
51
|
+
return "typescript"
|
|
52
|
+
return "javascript"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _text(data: bytes, node: Node) -> str:
|
|
56
|
+
"""Source text of ``node``, sliced from the bytes we parsed (cheaper than ``Node.text``)."""
|
|
57
|
+
return data[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _walk(node: Node) -> list[Node]:
|
|
61
|
+
out, stack = [], [node]
|
|
62
|
+
while stack:
|
|
63
|
+
current = stack.pop()
|
|
64
|
+
out.append(current)
|
|
65
|
+
stack.extend(reversed(current.children))
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _comment_text(raw: str) -> str:
|
|
70
|
+
if raw.startswith("//"):
|
|
71
|
+
return raw[2:].strip()
|
|
72
|
+
body = raw[2:-2] if raw.endswith("*/") else raw[2:]
|
|
73
|
+
lines = [line.strip().lstrip("*").strip() for line in body.splitlines()]
|
|
74
|
+
return " ".join(line for line in lines if line)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def looks_like_javascript(text: str, kind: str) -> bool:
|
|
78
|
+
"""Whether a line comment's text is commented-out code rather than prose."""
|
|
79
|
+
if not _CODE_HINT.search(text) or text.endswith((".", "?", "!", ":")):
|
|
80
|
+
return False
|
|
81
|
+
tree = _parser(kind).parse(text.encode("utf-8"))
|
|
82
|
+
return not tree.root_node.has_error and tree.root_node.named_child_count > 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _function_name(data: bytes, node: Node) -> str:
|
|
86
|
+
name = node.child_by_field_name("name")
|
|
87
|
+
if name is not None:
|
|
88
|
+
return _text(data, name)
|
|
89
|
+
parent = node.parent
|
|
90
|
+
if parent is not None and parent.type == "variable_declarator":
|
|
91
|
+
target = parent.child_by_field_name("name")
|
|
92
|
+
if target is not None:
|
|
93
|
+
return _text(data, target)
|
|
94
|
+
return "<anonymous>"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _declaration_start(node: Node) -> int:
|
|
98
|
+
"""Row where the statement declaring ``node`` starts (JSDoc sits right above it)."""
|
|
99
|
+
current = node
|
|
100
|
+
while current.parent is not None and current.parent.type in _DECLARATION_WRAPPERS:
|
|
101
|
+
current = current.parent
|
|
102
|
+
return current.start_point.row
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _statements(node: Node) -> int:
|
|
106
|
+
body = node.child_by_field_name("body")
|
|
107
|
+
if body is None:
|
|
108
|
+
return 0
|
|
109
|
+
if body.type == "statement_block" or body.type == "class_body":
|
|
110
|
+
return sum(1 for c in body.named_children if c.type != "comment")
|
|
111
|
+
return 1 # concise arrow body: one expression
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def parse_javascript(path: str, text: str) -> SourceFile | None:
|
|
115
|
+
kind = _grammar(path)
|
|
116
|
+
data = text.encode("utf-8")
|
|
117
|
+
tree = _parser(kind).parse(data)
|
|
118
|
+
nodes = _walk(tree.root_node)
|
|
119
|
+
lines = text.splitlines()
|
|
120
|
+
if tree.root_node.has_error:
|
|
121
|
+
error_rows: set[int] = set()
|
|
122
|
+
for node in nodes:
|
|
123
|
+
if node.type == "ERROR" or node.is_missing:
|
|
124
|
+
error_rows.update(range(node.start_point.row, node.end_point.row + 1))
|
|
125
|
+
if len(error_rows) > MAX_ERROR_SHARE * max(len(lines), 1):
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
comments: list[Comment] = []
|
|
129
|
+
docstring_rows: set[int] = set()
|
|
130
|
+
jsdoc_end_rows: set[int] = set()
|
|
131
|
+
code_rows: set[int] = set()
|
|
132
|
+
quote_styles: Counter[str] = Counter()
|
|
133
|
+
identifiers: list[str] = []
|
|
134
|
+
debug: list[tuple[int, str]] = []
|
|
135
|
+
function_nodes: list[Node] = []
|
|
136
|
+
|
|
137
|
+
for node in nodes:
|
|
138
|
+
kind_name = node.type
|
|
139
|
+
if kind_name == "comment":
|
|
140
|
+
raw = _text(data, node)
|
|
141
|
+
start, end = node.start_point.row, node.end_point.row
|
|
142
|
+
if raw.startswith("/**"):
|
|
143
|
+
docstring_rows.update(range(start, end + 1))
|
|
144
|
+
jsdoc_end_rows.add(end)
|
|
145
|
+
continue
|
|
146
|
+
before = lines[start][: node.start_point.column] if start < len(lines) else ""
|
|
147
|
+
comments.append(
|
|
148
|
+
Comment(start + 1, _comment_text(raw), not before.strip(), end - start + 1)
|
|
149
|
+
)
|
|
150
|
+
continue
|
|
151
|
+
if node.child_count == 0 and kind_name not in {"comment", "ERROR"}:
|
|
152
|
+
code_rows.update(range(node.start_point.row, node.end_point.row + 1))
|
|
153
|
+
if kind_name == "string" and _text(data, node)[:1] in {"'", '"'}:
|
|
154
|
+
quote_styles[_text(data, node)[0]] += 1
|
|
155
|
+
elif kind_name in _FUNCTIONS:
|
|
156
|
+
function_nodes.append(node)
|
|
157
|
+
elif kind_name == "debugger_statement":
|
|
158
|
+
debug.append((node.start_point.row + 1, "debugger"))
|
|
159
|
+
elif kind_name == "call_expression":
|
|
160
|
+
callee = node.child_by_field_name("function")
|
|
161
|
+
args = node.child_by_field_name("arguments")
|
|
162
|
+
if callee is not None and callee.type == "member_expression" and args is not None:
|
|
163
|
+
obj, prop = callee.child_by_field_name("object"), callee.child_by_field_name(
|
|
164
|
+
"property"
|
|
165
|
+
) # fmt: skip
|
|
166
|
+
first = args.named_children[0] if args.named_children else None
|
|
167
|
+
if (
|
|
168
|
+
obj is not None
|
|
169
|
+
and prop is not None
|
|
170
|
+
and _text(data, obj) == "console"
|
|
171
|
+
and _text(data, prop) in _CONSOLE
|
|
172
|
+
and first is not None
|
|
173
|
+
and first.type == "string"
|
|
174
|
+
and _text(data, first)[1:-1].strip(" .!:").lower() in DEBUG_WORDS
|
|
175
|
+
):
|
|
176
|
+
debug.append((node.start_point.row + 1, _text(data, node)[:60])) # fmt: skip
|
|
177
|
+
if kind_name == "variable_declarator":
|
|
178
|
+
name = node.child_by_field_name("name")
|
|
179
|
+
if name is not None and name.type == "identifier":
|
|
180
|
+
identifiers.append(_text(data, name))
|
|
181
|
+
elif kind_name in {"required_parameter", "optional_parameter"}:
|
|
182
|
+
pattern = node.child_by_field_name("pattern")
|
|
183
|
+
if pattern is not None and pattern.type == "identifier":
|
|
184
|
+
identifiers.append(_text(data, pattern))
|
|
185
|
+
elif kind_name == "formal_parameters":
|
|
186
|
+
identifiers += [_text(data, c) for c in node.named_children if c.type == "identifier"]
|
|
187
|
+
elif kind_name in {"class_declaration", "class"}:
|
|
188
|
+
name = node.child_by_field_name("name")
|
|
189
|
+
if name is not None:
|
|
190
|
+
identifiers.append(_text(data, name))
|
|
191
|
+
|
|
192
|
+
functions = []
|
|
193
|
+
for node in function_nodes:
|
|
194
|
+
function_name = _function_name(data, node)
|
|
195
|
+
if (
|
|
196
|
+
node.type
|
|
197
|
+
in {"function_declaration", "method_definition", "generator_function_declaration"}
|
|
198
|
+
and function_name != "<anonymous>"
|
|
199
|
+
):
|
|
200
|
+
identifiers.append(function_name) # fmt: skip
|
|
201
|
+
functions.append(
|
|
202
|
+
Function(
|
|
203
|
+
name=function_name,
|
|
204
|
+
line=node.start_point.row + 1,
|
|
205
|
+
end_line=node.end_point.row + 1,
|
|
206
|
+
statements=_statements(node),
|
|
207
|
+
has_docstring=_declaration_start(node) - 1 in jsdoc_end_rows,
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
return SourceFile(
|
|
212
|
+
path=path,
|
|
213
|
+
language="typescript" if kind != "javascript" else "javascript",
|
|
214
|
+
lines=lines,
|
|
215
|
+
code_line_numbers={r + 1 for r in code_rows - docstring_rows},
|
|
216
|
+
comments=comments,
|
|
217
|
+
docstring_lines=len(docstring_rows),
|
|
218
|
+
functions=functions,
|
|
219
|
+
identifiers=identifiers,
|
|
220
|
+
quote_styles=quote_styles,
|
|
221
|
+
commented_code_lines=[
|
|
222
|
+
c.line
|
|
223
|
+
for c in comments
|
|
224
|
+
if c.own_line and c.line_count == 1 and looks_like_javascript(c.text, kind)
|
|
225
|
+
], # fmt: skip
|
|
226
|
+
debug_statements=debug,
|
|
227
|
+
)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Python parser, using the standard library (``ast`` + ``tokenize``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import io
|
|
7
|
+
import re
|
|
8
|
+
import tokenize
|
|
9
|
+
from collections import Counter
|
|
10
|
+
|
|
11
|
+
from ai_code_detector.source import DEBUG_WORDS, Comment, Function, SourceFile
|
|
12
|
+
|
|
13
|
+
_NON_CODE_TOKENS = {
|
|
14
|
+
tokenize.COMMENT,
|
|
15
|
+
tokenize.NL,
|
|
16
|
+
tokenize.NEWLINE,
|
|
17
|
+
tokenize.INDENT,
|
|
18
|
+
tokenize.DEDENT,
|
|
19
|
+
tokenize.ENCODING,
|
|
20
|
+
tokenize.ENDMARKER,
|
|
21
|
+
}
|
|
22
|
+
_CODE_HINT = re.compile(r"[(=\[]|^\s*(import|from|return|if|for|while|def|class)\b")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _docstring_node(node: ast.AST) -> ast.Constant | None:
|
|
26
|
+
body = getattr(node, "body", None)
|
|
27
|
+
if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant):
|
|
28
|
+
if isinstance(body[0].value.value, str):
|
|
29
|
+
return body[0].value
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def looks_like_python(text: str) -> bool:
|
|
34
|
+
"""Whether a comment's text is commented-out code rather than prose."""
|
|
35
|
+
if not _CODE_HINT.search(text) or text.endswith((".", "?", "!")):
|
|
36
|
+
return False
|
|
37
|
+
try:
|
|
38
|
+
ast.parse(text)
|
|
39
|
+
except SyntaxError:
|
|
40
|
+
return False
|
|
41
|
+
return True
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def parse_python(path: str, text: str) -> SourceFile | None:
|
|
45
|
+
"""Analyse ``text``; ``None`` if it is not valid Python."""
|
|
46
|
+
try:
|
|
47
|
+
tree = ast.parse(text)
|
|
48
|
+
tokens = list(tokenize.generate_tokens(io.StringIO(text).readline))
|
|
49
|
+
except (SyntaxError, ValueError, tokenize.TokenError, RecursionError):
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
docstring_line_numbers: set[int] = set()
|
|
53
|
+
functions: list[Function] = []
|
|
54
|
+
identifiers: list[str] = []
|
|
55
|
+
debug: list[tuple[int, str]] = []
|
|
56
|
+
|
|
57
|
+
for node in ast.walk(tree):
|
|
58
|
+
doc = _docstring_node(node) if isinstance(
|
|
59
|
+
node, ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef
|
|
60
|
+
) else None # fmt: skip
|
|
61
|
+
if doc is not None and doc.end_lineno is not None:
|
|
62
|
+
docstring_line_numbers.update(range(doc.lineno, doc.end_lineno + 1))
|
|
63
|
+
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
64
|
+
body = node.body[1:] if doc is not None else node.body
|
|
65
|
+
functions.append(
|
|
66
|
+
Function(node.name, node.lineno, node.end_lineno or node.lineno, len(body),
|
|
67
|
+
doc is not None)
|
|
68
|
+
) # fmt: skip
|
|
69
|
+
identifiers.append(node.name)
|
|
70
|
+
for arg in [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs]:
|
|
71
|
+
if arg.arg not in {"self", "cls"}:
|
|
72
|
+
identifiers.append(arg.arg)
|
|
73
|
+
elif isinstance(node, ast.ClassDef):
|
|
74
|
+
identifiers.append(node.name)
|
|
75
|
+
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
|
76
|
+
identifiers.append(node.id)
|
|
77
|
+
elif isinstance(node, ast.Call):
|
|
78
|
+
name = (
|
|
79
|
+
node.func.id if isinstance(node.func, ast.Name)
|
|
80
|
+
else node.func.attr if isinstance(node.func, ast.Attribute) else ""
|
|
81
|
+
) # fmt: skip
|
|
82
|
+
first = node.args[0] if node.args else None
|
|
83
|
+
literal = first.value if isinstance(first, ast.Constant) else None
|
|
84
|
+
if (
|
|
85
|
+
name == "print"
|
|
86
|
+
and isinstance(literal, str)
|
|
87
|
+
and literal.strip(" .!:").lower() in DEBUG_WORDS
|
|
88
|
+
):
|
|
89
|
+
debug.append((node.lineno, f'print("{literal}")'))
|
|
90
|
+
elif name in {"breakpoint", "set_trace"}:
|
|
91
|
+
debug.append((node.lineno, f"{name}()"))
|
|
92
|
+
elif isinstance(node, ast.Import | ast.ImportFrom):
|
|
93
|
+
modules = [a.name for a in node.names] if isinstance(node, ast.Import) else [
|
|
94
|
+
node.module or ""
|
|
95
|
+
] # fmt: skip
|
|
96
|
+
debug += [(node.lineno, f"import {m}") for m in modules if m in {"pdb", "ipdb"}]
|
|
97
|
+
|
|
98
|
+
code_lines: set[int] = set()
|
|
99
|
+
comments: list[Comment] = []
|
|
100
|
+
quote_styles: Counter[str] = Counter()
|
|
101
|
+
for tok in tokens:
|
|
102
|
+
if tok.type == tokenize.COMMENT:
|
|
103
|
+
before = tok.line[: tok.start[1]]
|
|
104
|
+
comments.append(
|
|
105
|
+
Comment(tok.start[0], tok.string.lstrip("#").strip(), not before.strip())
|
|
106
|
+
)
|
|
107
|
+
elif tok.type not in _NON_CODE_TOKENS:
|
|
108
|
+
code_lines.update(range(tok.start[0], tok.end[0] + 1))
|
|
109
|
+
if tok.type == tokenize.STRING:
|
|
110
|
+
literal = tok.string.lstrip("rRbBuUfF")
|
|
111
|
+
if (
|
|
112
|
+
not literal.startswith(('"""', "'''"))
|
|
113
|
+
and tok.start[0] not in docstring_line_numbers
|
|
114
|
+
):
|
|
115
|
+
quote_styles[literal[0]] += 1
|
|
116
|
+
|
|
117
|
+
return SourceFile(
|
|
118
|
+
path=path,
|
|
119
|
+
language="python",
|
|
120
|
+
lines=text.splitlines(),
|
|
121
|
+
code_line_numbers=code_lines - docstring_line_numbers,
|
|
122
|
+
comments=comments,
|
|
123
|
+
docstring_lines=len(docstring_line_numbers),
|
|
124
|
+
functions=functions,
|
|
125
|
+
identifiers=identifiers,
|
|
126
|
+
quote_styles=quote_styles,
|
|
127
|
+
commented_code_lines=[c.line for c in comments if c.own_line and looks_like_python(c.text)],
|
|
128
|
+
debug_statements=debug,
|
|
129
|
+
)
|