path
stringlengths 15
77
| type
stringclasses 1
value | project
stringclasses 1
value | commit_hash
stringlengths 40
40
| commit_message
stringlengths 15
198
| ground_truth
stringlengths 26
155
| main_code
stringlengths 176
2.5k
| context
stringlengths 91
9.37k
|
---|---|---|---|---|---|---|---|
tests.coeditor.test_code_change/test_change_scope | Modified | temp-1 | 88a80dd462a4273154c266f5ef7d055f0b4fbfaf | Fix new scope headers. Fix unit tests. | <0>:<add> assert_str_equal(inner_class_code, indent(inner_attr1_expect, " " * 4))
| # module: tests.coeditor.test_code_change
def test_change_scope():
<s>code, indent(f1_expect, " " * 4))
- assert_str_equal(f1_code, f1_expect)
f2_expect = dedent(
"""\
@annotated
def f2():
return 1
"""
)
+ f2_code = scope.subscopes[ProjectPath("code1", "f2")].all_code
- f2_code = scope.subscopes[ProjectPath("code1", "f2")].spans_code
assert_str_equal(f2_code, f2_expect)
attr1_expect = dedent(
"""\
attr1: int
"""
)
attr1_code = scope.subscopes[ProjectPath("code1", "A")].spans_code
assert_str_equal(attr1_code, indent(attr1_expect, " " * 4))
method1_expect = dedent(
"""\
@staticmethod
def method1():
return 1
"""
)
method1_code = (
scope.subscopes[ProjectPath("code1", "A")]
.subscopes[ProjectPath("code1", "A.method1")]
+ .all_code
- .spans_code
)
assert_str_equal(method1_code, indent(method1_expect, " " * 4))
inner_attr1_expect = dedent(
"""\
+ class B:
+ inner_attr1: int
- inner_attr1: int
"""
)
+ inner_class_code = (
- inner_attr1_code = (
scope.subscopes[ProjectPath("code1", "A")]
.subscopes[ProjectPath("code1", "A.B")]
+ .all_code
- .spans_code
)
- assert_str_equal(inner_attr1_code, indent(inner_attr1_expect, " " * 8))
<0>
| ===========above chunk 0===========
# module: tests.coeditor.test_code_change
def test_change_scope():
# offset: -1
code1 = dedent(
"""\
import os
x = 1
y = x + 1
def f1():
global x
x *= 5
return x
if __name__ == "__main__":
print(f1() + x)
@annotated
def f2():
return 1
@dataclass
class A:
attr1: int
@staticmethod
def method1():
return 1
class B:
inner_attr1: int
"""
)
mod_tree = code_to_module(code1)
scope = ChangeScope.from_tree(ProjectPath("code1", ""), mod_tree)
global_spans = [
dedent(
"""\
x = 1
y = x + 1
"""
),
dedent(
"""\
if __name__ == "__main__":
print(f1() + x)
"""
),
]
for i, code in enumerate(global_spans):
assert_str_equal(scope.spans[i].code, code)
f1_expect = dedent(
"""\
- def f1():
+ global x
- global x
+ x *= 5
- x *= 5
+ return x
- return x
"""
)
f1_code = scope.subscopes[ProjectPath("code1", "f1")].spans_code
+ assert_str_equal(f1_code, indent(f1_expect, " " * 4))
- assert_str_equal(f1_code, f1</s>
===========unchanged ref 0===========
at: textwrap
indent(text: str, prefix: str, predicate: Optional[Callable[[str], bool]]=...) -> str
|
tests.coeditor.test_code_change/TestChangedSpan.test_comments_change | Modified | temp-1 | 88a80dd462a4273154c266f5ef7d055f0b4fbfaf | Fix new scope headers. Fix unit tests. | <0>:<add> (Modified, 1),
| # module: tests.coeditor.test_code_change
class TestChangedSpan:
def test_comments_change(self):
# have to update code as well for the changes to count
code2 = dedent(
"""\
import os
x = 1
# belongs to f1
def f1():
"added doc string"
global x
x *= 5
return x + 1
# belongs to main
if __name__ == "__main__":
print(f1() + x + 1) # belongs to print
"""
)
scope2 = ChangeScope.from_tree(ProjectPath("code1", ""), code_to_module(code2))
self.check_changed_spans(
get_changed_spans(Modified(self.scope1, scope2)),
(Modified, -1),
- (Modified, 3),
<0> (Modified, 1),
)
| ===========unchanged ref 0===========
at: tests.coeditor.test_code_change.TestChangedSpan
code1 = dedent(
"""\
import os
x = 1
y = x + 1
def f1():
global x
x *= 5
return x
if __name__ == "__main__":
print(f1() + x)
"""
)
scope1 = ChangeScope.from_tree(ProjectPath("code1", ""), code_to_module(code1))
check_changed_spans(changed_spans: Sequence[ChangedSpan], *expects: tuple[type, int])
===========changed ref 0===========
# module: tests.coeditor.test_code_change
def test_change_scope():
code1 = dedent(
"""\
import os
x = 1
y = x + 1
def f1():
global x
x *= 5
return x
if __name__ == "__main__":
print(f1() + x)
@annotated
def f2():
return 1
@dataclass
class A:
attr1: int
@staticmethod
def method1():
return 1
class B:
inner_attr1: int
"""
)
mod_tree = code_to_module(code1)
scope = ChangeScope.from_tree(ProjectPath("code1", ""), mod_tree)
global_spans = [
dedent(
"""\
x = 1
y = x + 1
"""
),
dedent(
"""\
if __name__ == "__main__":
print(f1() + x)
"""
),
]
for i, code in enumerate(global_spans):
assert_str_equal(scope.spans[i].code, code)
f1_expect = dedent(
"""\
- def f1():
+ global x
- global x
+ x *= 5
- x *= 5
+ return x
- return x
"""
)
f1_code = scope.subscopes[ProjectPath("code1", "f1")].spans_code
+ assert_str_equal(f1_code, indent(f1_expect, " " * 4))
- assert_str_equal(f1_code, f1_expect)
f2_expect = dedent(
"""\
@annotated
def f2():
return 1
"""
)
+ f2_code = scope.subscopes[ProjectPath("code1", "f2")].all_code
- f2_code = scope.</s>
===========changed ref 1===========
# module: tests.coeditor.test_code_change
def test_change_scope():
# offset: 1
<s> = scope.subscopes[ProjectPath("code1", "f2")].all_code
- f2_code = scope.subscopes[ProjectPath("code1", "f2")].spans_code
assert_str_equal(f2_code, f2_expect)
attr1_expect = dedent(
"""\
attr1: int
"""
)
attr1_code = scope.subscopes[ProjectPath("code1", "A")].spans_code
assert_str_equal(attr1_code, indent(attr1_expect, " " * 4))
method1_expect = dedent(
"""\
@staticmethod
def method1():
return 1
"""
)
method1_code = (
scope.subscopes[ProjectPath("code1", "A")]
.subscopes[ProjectPath("code1", "A.method1")]
+ .all_code
- .spans_code
)
assert_str_equal(method1_code, indent(method1_expect, " " * 4))
inner_attr1_expect = dedent(
"""\
+ class B:
+ inner_attr1: int
- inner_attr1: int
"""
)
+ inner_class_code = (
- inner_attr1_code = (
scope.subscopes[ProjectPath("code1", "A")]
.subscopes[ProjectPath("code1", "A.B")]
+ .all_code
- .spans_code
)
+ assert_str_equal(inner_class_code, indent(inner_attr1_expect, " " * 4))
- assert_str_equal(inner_attr1_code, indent(inner_attr1_expect, " " * 8))
|
coeditor.code_change/ChangeScope.header_code | Modified | temp-1 | 88a80dd462a4273154c266f5ef7d055f0b4fbfaf | Fix new scope headers. Fix unit tests. | <0>:<add> return "".join(snippets)
| # module: coeditor.code_change
@dataclass
class ChangeScope:
@cached_property
def header_code(self) -> str:
if isinstance(self.tree, ptree.Module):
return f"# module: {self.path.module}"
# get the first non-empty line of self.tree
+ tree = self.tree
+ to_visit = []
+ parent = not_none(tree.parent)
+ while parent.type in ("decorated", "async_funcdef"):
+ to_visit.insert(0, parent.children[0])
+ parent = not_none(parent.parent)
+ to_visit.extend(tree.children)
+
+ snippets = list[str]()
- first_line = "#" if isinstance(self.tree, ptree.Function) else ""
+ for i, c in enumerate(to_visit):
- for i, c in enumerate(self.tree.children):
+ if c.type == "suite":
+ break
snippet = cast(str, c.get_code())
if i == 0:
# remove leading newlines
snippet = snippet.lstrip("\n")
assert isinstance(snippet, str)
- if count_lines(snippet) == 1:
- first_line += snippet
- else:
- first_line += snippet.splitlines()[0]
- break
- return first_line
+ snippets.append(snippet)
<0>
| ===========unchanged ref 0===========
at: coeditor._utils
not_none(x: Optional[T1]) -> T1
at: coeditor.code_change.ChangeScope
path: ProjectPath
tree: ScopeTree
spans: Sequence["StatementSpan"]
subscopes: Mapping[ProjectPath, Self]
at: functools
cached_property(func: Callable[[Any], _T])
at: parso.python.tree
Module(children)
at: parso.tree.BaseNode.__init__
self.children = children
self.parent: Optional[BaseNode] = None
at: parso.tree.NodeOrLeaf
__slots__ = ('parent',)
type: str
parent: 'Optional[BaseNode]'
at: spot.static_analysis.ProjectPath
module: ModuleName
path: ElemPath
===========changed ref 0===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ @cached_property
+ def all_code(self) -> str:
+ return f"{self.header_code}\n{self.spans_code}"
+
===========changed ref 1===========
# module: coeditor.code_change
+ ScopeTree = ptree.Function | ptree.Class | ptree.Module
- ScopeTree = ptree.Module | ptree.Function | ptree.Class
PyNode = ptree.PythonBaseNode | ptree.PythonNode
_tlogger = TimeLogger()
===========changed ref 2===========
# module: tests.coeditor.test_code_change
class TestChangedSpan:
def test_comments_change(self):
# have to update code as well for the changes to count
code2 = dedent(
"""\
import os
x = 1
# belongs to f1
def f1():
"added doc string"
global x
x *= 5
return x + 1
# belongs to main
if __name__ == "__main__":
print(f1() + x + 1) # belongs to print
"""
)
scope2 = ChangeScope.from_tree(ProjectPath("code1", ""), code_to_module(code2))
self.check_changed_spans(
get_changed_spans(Modified(self.scope1, scope2)),
(Modified, -1),
+ (Modified, 1),
- (Modified, 3),
(Modified, 1),
)
===========changed ref 3===========
# module: tests.coeditor.test_code_change
def test_change_scope():
code1 = dedent(
"""\
import os
x = 1
y = x + 1
def f1():
global x
x *= 5
return x
if __name__ == "__main__":
print(f1() + x)
@annotated
def f2():
return 1
@dataclass
class A:
attr1: int
@staticmethod
def method1():
return 1
class B:
inner_attr1: int
"""
)
mod_tree = code_to_module(code1)
scope = ChangeScope.from_tree(ProjectPath("code1", ""), mod_tree)
global_spans = [
dedent(
"""\
x = 1
y = x + 1
"""
),
dedent(
"""\
if __name__ == "__main__":
print(f1() + x)
"""
),
]
for i, code in enumerate(global_spans):
assert_str_equal(scope.spans[i].code, code)
f1_expect = dedent(
"""\
- def f1():
+ global x
- global x
+ x *= 5
- x *= 5
+ return x
- return x
"""
)
f1_code = scope.subscopes[ProjectPath("code1", "f1")].spans_code
+ assert_str_equal(f1_code, indent(f1_expect, " " * 4))
- assert_str_equal(f1_code, f1_expect)
f2_expect = dedent(
"""\
@annotated
def f2():
return 1
"""
)
+ f2_code = scope.subscopes[ProjectPath("code1", "f2")].all_code
- f2_code = scope.</s>
===========changed ref 4===========
# module: tests.coeditor.test_code_change
def test_change_scope():
# offset: 1
<s> = scope.subscopes[ProjectPath("code1", "f2")].all_code
- f2_code = scope.subscopes[ProjectPath("code1", "f2")].spans_code
assert_str_equal(f2_code, f2_expect)
attr1_expect = dedent(
"""\
attr1: int
"""
)
attr1_code = scope.subscopes[ProjectPath("code1", "A")].spans_code
assert_str_equal(attr1_code, indent(attr1_expect, " " * 4))
method1_expect = dedent(
"""\
@staticmethod
def method1():
return 1
"""
)
method1_code = (
scope.subscopes[ProjectPath("code1", "A")]
.subscopes[ProjectPath("code1", "A.method1")]
+ .all_code
- .spans_code
)
assert_str_equal(method1_code, indent(method1_expect, " " * 4))
inner_attr1_expect = dedent(
"""\
+ class B:
+ inner_attr1: int
- inner_attr1: int
"""
)
+ inner_class_code = (
- inner_attr1_code = (
scope.subscopes[ProjectPath("code1", "A")]
.subscopes[ProjectPath("code1", "A.B")]
+ .all_code
- .spans_code
)
+ assert_str_equal(inner_class_code, indent(inner_attr1_expect, " " * 4))
- assert_str_equal(inner_attr1_code, indent(inner_attr1_expect, " " * 8))
|
coeditor.code_change/ChangeScope.from_tree | Modified | temp-1 | 88a80dd462a4273154c266f5ef7d055f0b4fbfaf | Fix new scope headers. Fix unit tests. | <0>:<add> subscopes[spath] = subscope
| # module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
<s>as_any(s)):
- current_stmts.append(s)
- else:
- if current_stmts:
- spans.append(StatementSpan(current_stmts))
- current_stmts = []
- if current_stmts:
- spans.append(StatementSpan(current_stmts))
+ current_stmts = []
+ content = (
+ tree.children
+ if isinstance(tree, ptree.Module)
+ else cast(ptree.PythonNode, tree.get_suite()).children
+ )
+ for s in content:
+ # we don't create inner scopes for function contents
+ if is_func or _is_scope_statement(as_any(s)):
+ current_stmts.append(s)
+ else:
+ if current_stmts:
+ spans.append(StatementSpan(current_stmts))
+ current_stmts = []
+ if current_stmts:
+ spans.append(StatementSpan(current_stmts))
+
+ if is_func:
+ # we don't create inner scopes for function contents
+ return scope
+ for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
- for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
+ stree: ptree.Function | ptree.Class
- stree: ptree.Function | ptree.Class
+ spath = path.append(cast(ptree.Name, stree.name).value)
- spath = path.append(cast(ptree.Name, stree.name).value)
+ subscope = ChangeScope.from_tree(spath, stree)
- subscope = ChangeScope.from_tree(spath, stree)
- subscopes[spath] = subscope
<0> return scope
| ===========above chunk 0===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
# offset: -1
spans = []
subscopes = dict()
scope = ChangeScope(path, tree, spans, subscopes)
+ assert isinstance(tree, ScopeTree)
+ is_func = isinstance(tree, ptree.Function)
- if isinstance(tree, ptree.Function):
- span = StatementSpan([_to_decorated(tree)])
- spans.append(span)
- else:
- assert isinstance(tree, (ptree.Module, ptree.Class))
- current_stmts = []
- content = (
- tree.children
- if isinstance(tree, ptree.Module)
- else cast(ptree.PythonNode, tree.get_suite()).children
- )
- for s in content:
- if _is_scope_statement(as_any(s)):
- current_stmts.append(s)
- else:
- if current_stmts</s>
===========unchanged ref 0===========
at: coeditor._utils
as_any(x) -> Any
at: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
ChangeScope(path: ProjectPath, tree: ScopeTree, spans: Sequence["StatementSpan"], subscopes: Mapping[ProjectPath, Self])
_is_scope_statement(stmt: PyNode) -> bool
StatementSpan(statements: Sequence[PyNode])
at: coeditor.code_change.ChangeScope.header_code
snippets = list[str]()
at: parso.python.tree
PythonNode()
Module(children)
Function(children)
at: parso.python.tree.Scope
__slots__ = ()
get_suite()
at: parso.tree.BaseNode.__init__
self.children = children
at: parso.tree.NodeOrLeaf
type: str
get_code(include_prefix=True)
at: spot.static_analysis
ProjectPath(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any)
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
===========changed ref 0===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ @cached_property
+ def all_code(self) -> str:
+ return f"{self.header_code}\n{self.spans_code}"
+
===========changed ref 1===========
# module: coeditor.code_change
+ ScopeTree = ptree.Function | ptree.Class | ptree.Module
- ScopeTree = ptree.Module | ptree.Function | ptree.Class
PyNode = ptree.PythonBaseNode | ptree.PythonNode
_tlogger = TimeLogger()
===========changed ref 2===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@cached_property
def header_code(self) -> str:
if isinstance(self.tree, ptree.Module):
return f"# module: {self.path.module}"
# get the first non-empty line of self.tree
+ tree = self.tree
+ to_visit = []
+ parent = not_none(tree.parent)
+ while parent.type in ("decorated", "async_funcdef"):
+ to_visit.insert(0, parent.children[0])
+ parent = not_none(parent.parent)
+ to_visit.extend(tree.children)
+
+ snippets = list[str]()
- first_line = "#" if isinstance(self.tree, ptree.Function) else ""
+ for i, c in enumerate(to_visit):
- for i, c in enumerate(self.tree.children):
+ if c.type == "suite":
+ break
snippet = cast(str, c.get_code())
if i == 0:
# remove leading newlines
snippet = snippet.lstrip("\n")
assert isinstance(snippet, str)
- if count_lines(snippet) == 1:
- first_line += snippet
- else:
- first_line += snippet.splitlines()[0]
- break
- return first_line
+ snippets.append(snippet)
+ return "".join(snippets)
===========changed ref 3===========
# module: tests.coeditor.test_code_change
class TestChangedSpan:
def test_comments_change(self):
# have to update code as well for the changes to count
code2 = dedent(
"""\
import os
x = 1
# belongs to f1
def f1():
"added doc string"
global x
x *= 5
return x + 1
# belongs to main
if __name__ == "__main__":
print(f1() + x + 1) # belongs to print
"""
)
scope2 = ChangeScope.from_tree(ProjectPath("code1", ""), code_to_module(code2))
self.check_changed_spans(
get_changed_spans(Modified(self.scope1, scope2)),
(Modified, -1),
+ (Modified, 1),
- (Modified, 3),
(Modified, 1),
)
===========changed ref 4===========
# module: tests.coeditor.test_code_change
def test_change_scope():
code1 = dedent(
"""\
import os
x = 1
y = x + 1
def f1():
global x
x *= 5
return x
if __name__ == "__main__":
print(f1() + x)
@annotated
def f2():
return 1
@dataclass
class A:
attr1: int
@staticmethod
def method1():
return 1
class B:
inner_attr1: int
"""
)
mod_tree = code_to_module(code1)
scope = ChangeScope.from_tree(ProjectPath("code1", ""), mod_tree)
global_spans = [
dedent(
"""\
x = 1
y = x + 1
"""
),
dedent(
"""\
if __name__ == "__main__":
print(f1() + x)
"""
),
]
for i, code in enumerate(global_spans):
assert_str_equal(scope.spans[i].code, code)
f1_expect = dedent(
"""\
- def f1():
+ global x
- global x
+ x *= 5
- x *= 5
+ return x
- return x
"""
)
f1_code = scope.subscopes[ProjectPath("code1", "f1")].spans_code
+ assert_str_equal(f1_code, indent(f1_expect, " " * 4))
- assert_str_equal(f1_code, f1_expect)
f2_expect = dedent(
"""\
@annotated
def f2():
return 1
"""
)
+ f2_code = scope.subscopes[ProjectPath("code1", "f2")].all_code
- f2_code = scope.</s> |
coeditor.ctx_change_encoder/TkCtxCodeChangeEncoder._encode_parent_scopes | Modified | temp-1 | 88a80dd462a4273154c266f5ef7d055f0b4fbfaf | Fix new scope headers. Fix unit tests. | <0>:<add> return scope_tks
| # module: coeditor.ctx_change_encoder
@dataclass
class TkCtxCodeChangeEncoder:
def _encode_parent_scopes(
self, scope_changes: Sequence[Change[ChangeScope]], offset: int
) -> TokenSeq:
scope_tks = join_list(
(self._encode_scope_change(c) for c in scope_changes), sep=Newline_id
)
if offset != 0:
ending = encode_basic(f"\n# offset: {offset}\n")
else:
ending = [Newline_id]
+ scope_tks = truncate_section(
+ scope_tks + ending, TruncateAt.Left, self.max_scope_tks
+ )
- return scope_tks + ending
<0>
| ===========unchanged ref 0===========
at: coeditor.common
TokenSeq = list[Token]
join_list(segs: Iterable[Iterable[T1]], sep: T1 | None=None) -> list[T1]
at: coeditor.ctx_change_encoder.TkCtxCodeChangeEncoder
VERSION = "0.0"
max_ref_tks: int = 512
max_query_tks: int = 512
max_output_tks: int = 256
max_scope_tks: int = 128
max_lines_to_edit: int = 20
ref_chunk_overlap: int = 32
max_chunks_per_ref: int = 4
max_lines_per_function: int = 500
skip_unchanged_problems: bool = True
_encode_scope_change(c: Change[ChangeScope]) -> TokenSeq
at: coeditor.encoding
Newline_id = get_tk_id("\n")
truncate_section(sec: TokenSeq, direction: TruncateAt.Value, limit: int, add_bos: bool=True, inplace: bool=False) -> TokenSeq
at: typing
Sequence = _alias(collections.abc.Sequence, 1)
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
@dataclass
class TkCtxCodeChangeEncoder:
VERSION = "0.0"
max_ref_tks: int = 512
max_query_tks: int = 512
max_output_tks: int = 256
+ max_scope_tks: int = 128
- max_scope_tks: int = 50
max_lines_to_edit: int = 20
ref_chunk_overlap: int = 32
max_chunks_per_ref: int = 4
max_lines_per_function: int = 500
skip_unchanged_problems: bool = True
===========changed ref 1===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ @cached_property
+ def all_code(self) -> str:
+ return f"{self.header_code}\n{self.spans_code}"
+
===========changed ref 2===========
# module: coeditor.code_change
+ ScopeTree = ptree.Function | ptree.Class | ptree.Module
- ScopeTree = ptree.Module | ptree.Function | ptree.Class
PyNode = ptree.PythonBaseNode | ptree.PythonNode
_tlogger = TimeLogger()
===========changed ref 3===========
# module: tests.coeditor.test_code_change
class TestChangedSpan:
def test_comments_change(self):
# have to update code as well for the changes to count
code2 = dedent(
"""\
import os
x = 1
# belongs to f1
def f1():
"added doc string"
global x
x *= 5
return x + 1
# belongs to main
if __name__ == "__main__":
print(f1() + x + 1) # belongs to print
"""
)
scope2 = ChangeScope.from_tree(ProjectPath("code1", ""), code_to_module(code2))
self.check_changed_spans(
get_changed_spans(Modified(self.scope1, scope2)),
(Modified, -1),
+ (Modified, 1),
- (Modified, 3),
(Modified, 1),
)
===========changed ref 4===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@cached_property
def header_code(self) -> str:
if isinstance(self.tree, ptree.Module):
return f"# module: {self.path.module}"
# get the first non-empty line of self.tree
+ tree = self.tree
+ to_visit = []
+ parent = not_none(tree.parent)
+ while parent.type in ("decorated", "async_funcdef"):
+ to_visit.insert(0, parent.children[0])
+ parent = not_none(parent.parent)
+ to_visit.extend(tree.children)
+
+ snippets = list[str]()
- first_line = "#" if isinstance(self.tree, ptree.Function) else ""
+ for i, c in enumerate(to_visit):
- for i, c in enumerate(self.tree.children):
+ if c.type == "suite":
+ break
snippet = cast(str, c.get_code())
if i == 0:
# remove leading newlines
snippet = snippet.lstrip("\n")
assert isinstance(snippet, str)
- if count_lines(snippet) == 1:
- first_line += snippet
- else:
- first_line += snippet.splitlines()[0]
- break
- return first_line
+ snippets.append(snippet)
+ return "".join(snippets)
===========changed ref 5===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
spans = []
subscopes = dict()
scope = ChangeScope(path, tree, spans, subscopes)
+ assert isinstance(tree, ScopeTree)
+ is_func = isinstance(tree, ptree.Function)
- if isinstance(tree, ptree.Function):
- span = StatementSpan([_to_decorated(tree)])
- spans.append(span)
- else:
- assert isinstance(tree, (ptree.Module, ptree.Class))
- current_stmts = []
- content = (
- tree.children
- if isinstance(tree, ptree.Module)
- else cast(ptree.PythonNode, tree.get_suite()).children
- )
- for s in content:
- if _is_scope_statement(as_any(s)):
- current_stmts.append(s)
- else:
- if current_stmts:
- spans.append(StatementSpan(current_stmts))
- current_stmts = []
- if current_stmts:
- spans.append(StatementSpan(current_stmts))
+ current_stmts = []
+ content = (
+ tree.children
+ if isinstance(tree, ptree.Module)
+ else cast(ptree.PythonNode, tree.get_suite()).children
+ )
+ for s in content:
+ # we don't create inner scopes for function contents
+ if is_func or _is_scope_statement(as_any(s)):
+ current_stmts.append(s)
+ else:
+ if current_stmts:
+ spans.append(StatementSpan(current_stmts))
+ current_stmts = []
+ if current_stmts:
+ spans.append(StatementSpan(current_stmts))
+
+ if is_func:
+ # we don't create inner scopes for function contents
+ return scope</s>
===========changed ref 6===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
# offset: 1
<s>stmts))
+
+ if is_func:
+ # we don't create inner scopes for function contents
+ return scope
+ for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
- for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
+ stree: ptree.Function | ptree.Class
- stree: ptree.Function | ptree.Class
+ spath = path.append(cast(ptree.Name, stree.name).value)
- spath = path.append(cast(ptree.Name, stree.name).value)
+ subscope = ChangeScope.from_tree(spath, stree)
- subscope = ChangeScope.from_tree(spath, stree)
+ subscopes[spath] = subscope
- subscopes[spath] = subscope
return scope
|
coeditor.ctx_change_encoder/CtxCodeChangeProblemGenerator.encode_change | Modified | temp-1 | 02aa6e2654a126be45b9b14e746d5bf2ad329e65 | Fix static analysis. | <0>:<add> result.append((ProjectPath(used.full_name, ""), str(used)))
| # module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def encode_change(
self,
pchange: JProjectChange,
mod2usages: Mapping[ModuleName, LineUsageAnalysis],
module_order: Sequence[ModuleName],
) -> Iterable[CtxCodeChangeProblem]:
<s> _get_relevant(span: ChangedSpan):
if isinstance(span.change, Added):
# nothing to analyze
return []
path = span.parent_scopes[-1].earlier().path
line_usages = mod2usages[path.module]
+ all_used = set[PyDefinition]()
- all_used = set[PyFullName]()
l_start, l_end = span.line_range
for l in range(l_start, l_end + 1):
+ for pydef in line_usages.line2usages.get(l, set()):
+ if (
+ pydef.module == path.module
+ and l_start <= pydef.start_pos[0] <= l_end
+ ):
+ # skip self references
+ print(f"Skip: {pydef}")
+ continue
+ all_used.add(pydef)
- all_used.update(line_usages.line2usages.get(l, tuple()))
result = list[tuple[ProjectPath, str]]()
for used in all_used:
- result.append((ProjectPath("?", used), used))
<0> return result
sorted_cspans = list[ChangedSpan]()
for m in module_order:
if (mchange := pchange.changed.get(m)) is None:
continue
for span in mchange.changed.values():
if span.change.as_char() == Modified.as_char():
yield CtxCodeChangeProblem(
span,
relevant_changes=sorted_cspans.copy(),
relevant_unchanged=_get_relevant(span),
)
sorted_cspans.append(span)
| ===========above chunk 0===========
# module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def encode_change(
self,
pchange: JProjectChange,
mod2usages: Mapping[ModuleName, LineUsageAnalysis],
module_order: Sequence[ModuleName],
) -> Iterable[CtxCodeChangeProblem]:
# offset: -1
def _get_relevant(span: ChangedSpan):
if isinstance(span.change, Added):
# nothing to analyze
return</s>
===========unchanged ref 0===========
at: coeditor.common
RelPath = NewType("RelPath", Path)
at: coeditor.ctx_change_encoder
CtxCodeChangeProblem(span: ChangedSpan, relevant_changes: list[ChangedSpan], relevant_unchanged: list[tuple[ProjectPath, str]])
LineUsageAnalysis(line2usages: Mapping[int, set[PyDefinition]])
fast_goto(script: jedi.Script, tree_name: tree.Name, *, follow_imports=False, follow_builtin_imports=False, only_stubs=False, prefer_stubs=False) -> set[classes.Name]
at: coeditor.ctx_change_encoder.CtxCodeChangeProblemGenerator.__init__
self.analysis = analysis
at: coeditor.ctx_change_encoder.CtxCodeChangeProblemGenerator.pre_edit_analysis
jmod = modules[mod_path]
script = jedi.Script(path=project.path / mod_path, project=project)
at: coeditor.ctx_change_encoder.JediUsageAnalysis
follow_imports: bool = True
only_same_project_usages: bool = False
get_module_usages(self, script: jedi.Script, proj_root: Path, silent: bool=False)
get_module_usages(script: jedi.Script, proj_root: Path, silent: bool=False)
at: jedi.api
Script(code=None, *, path=None, environment=None, project=None)
at: jedi.api.Script.__init__
self._module_node, code = self._inference_state.parse_and_get_code(
code=code,
path=self.path,
use_latest_grammar=path and path.suffix == '.pyi',
cache=False, # No disk cache, because the current script often changes.
diff_cache=settings.fast_parser,
cache_path=settings.cache_directory,
)
===========unchanged ref 1===========
at: jedi.api.project
Project(path, *, environment_path=None, load_unsafe_extensions=False, sys_path=None, added_sys_path=(), smart_sys_path=True)
at: jedi.api.project.Project
_environment = None
at: jedi.api.project.Project.__init__
self._path = path
at: pathlib.Path
__slots__ = ()
exists() -> bool
at: spot.static_analysis
ModuleName = str
sort_modules_by_imports(imports: Mapping[ModuleName, set[ModuleName]]) -> list[ModuleName]
at: typing
Iterable = _alias(collections.abc.Iterable, 1)
Mapping = _alias(collections.abc.Mapping, 2)
Sequence = _alias(collections.abc.Sequence, 1)
at: typing.Mapping
items() -> AbstractSet[Tuple[_KT, _VT_co]]
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
@dataclass
class LineUsageAnalysis:
+ line2usages: Mapping[int, set[PyDefinition]]
- line2usages: dict[int, set[PyFullName]]
===========changed ref 1===========
# module: coeditor.ctx_change_encoder
+ @dataclass(unsafe_hash=True)
+ class PyDefinition:
+ full_name: PyFullName
+ module: ModuleName
+ file: Path
+ start_pos: tuple[int, int]
+ end_pos: tuple[int, int]
+
===========changed ref 2===========
# module: coeditor.ctx_change_encoder
+ @dataclass(unsafe_hash=True)
+ class PyDefinition:
+ @staticmethod
+ def from_signatures(
+ name: classes.BaseName, project: Path | None = None
+ ) -> Iterable["PyDefinition"]:
+ if name.in_builtin_module():
+ return
+ for sig in name.get_signatures():
+ if (
+ not sig.in_builtin_module()
+ and (full_name := sig.full_name)
+ and (file := sig.module_path)
+ and (project in file.parents)
+ and (module := sig.module_name)
+ and (start_pos := sig.get_definition_start_position())
+ and (end_pos := sig.get_definition_end_position())
+ ):
+ full_name = PyFullName(full_name)
+ yield PyDefinition(full_name, module, file, start_pos, end_pos)
+ |
coeditor.ctx_change_encoder/JediUsageAnalysis.get_module_usages | Modified | temp-1 | 02aa6e2654a126be45b9b14e746d5bf2ad329e65 | Fix static analysis. | <0>:<add> errors[repr(e)] = errors.setdefault(str(e), 0) + 1
| # module: coeditor.ctx_change_encoder
@dataclass
class JediUsageAnalysis:
def get_module_usages(
self, script: jedi.Script, proj_root: Path, silent: bool = False
):
<s> all_names.sort(key=lambda x: x.start_pos)
errors = self.error_counts
+ resolve_cache = dict[_ObjId, set[PyDefinition]]()
for name in tqdm(all_names, f"Analyzing {script.path}", disable=silent):
name: tree.Name
line = name.start_pos[0]
usages = line2usages.setdefault(line, set())
try:
defs = fast_goto(
script,
name,
follow_imports=self.follow_imports,
follow_builtin_imports=False,
)
for d in defs:
- if (
- d.module_path
- and d.full_name
- and (
- not self.only_same_project_usages
- or (proj_root in d.module_path.parents)
- )
- ):
- usages.add(PyFullName(d.full_name))
+ key = _ObjId(id(d))
+ if (defs := resolve_cache.get(key)) is None:
+ defs = set(PyDefinition.from_signatures(d, proj_root))
+ resolve_cache[key] = defs
+ usages.update(defs)
+
except (AttributeError, AssertionError) as e:
+ text = repr(e)
- text = str(e)
errors[text] = errors.setdefault(text, 0) + 1
except ValueError as e:
# if the message is "not enough values to unpack"
if "not enough values to unpack (expected 2" in str(e):
- errors[str(e)] = errors.setdefault(str(e), 0) + 1
<0> else:
raise
return LineUsageAnalysis(line2usages)
| ===========above chunk 0===========
# module: coeditor.ctx_change_encoder
@dataclass
class JediUsageAnalysis:
def get_module_usages(
self, script: jedi.Script, proj_root: Path, silent: bool = False
):
# offset: -1
jmod: tree.Module = script._module_node
+ line2usages = dict[int, set[PyDefinition]]()
- line2usages = dict[int, set[PyFullName]]()
all_names = [
name for k, names in jmod.get_used_names()._dict.items() for name in names
]
all_names.sort(key=lambda x: x.start_pos)
errors = self.error_counts
+ resolve</s>
===========unchanged ref 0===========
at: coeditor._utils
TimeLogger(times: dict[str, list[float]]=field(default_factory=dict))
at: coeditor.ctx_change_encoder
PyDefinition(full_name: PyFullName, module: ModuleName, file: Path, start_pos: tuple[int, int], end_pos: tuple[int, int])
at: coeditor.ctx_change_encoder.TkCtxCodeChangeEncoder
VERSION = "0.0"
max_ref_tks: int = 512
max_query_tks: int = 512
max_output_tks: int = 256
max_scope_tks: int = 128
max_lines_to_edit: int = 20
ref_chunk_overlap: int = 32
max_chunks_per_ref: int = 4
max_lines_per_function: int = 500
skip_unchanged_problems: bool = True
_encode_parent_scopes(scope_changes: Sequence[Change[ChangeScope]], offset: int) -> TokenSeq
_encode_change(change: Change[str]) -> TokenSeq
at: coeditor.ctx_change_encoder.TkCtxCodeChangeEncoder._group_encode_changed_refs
all_chunks = list[TokenSeq]()
file_tks = TokenSeq()
at: coeditor.encoding
Newline_id = get_tk_id("\n")
break_into_chunks(tks: TokenSeq, header_f: Callable[[int], TokenSeq], chunk_size: int, overlap: int, right_to_left: bool=False, add_bos: bool=True, max_return_chunks: int | None=None) -> list[TokenSeq]
===========unchanged ref 1===========
at: dataclasses
dataclass(_cls: Type[_T]) -> Type[_T]
dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]]
dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]
at: jedi.api
Script(code=None, *, path=None, environment=None, project=None)
at: jedi.api.Script.__init__
self._module_node, code = self._inference_state.parse_and_get_code(
code=code,
path=self.path,
use_latest_grammar=path and path.suffix == '.pyi',
cache=False, # No disk cache, because the current script often changes.
diff_cache=settings.fast_parser,
cache_path=settings.cache_directory,
)
at: parso.python.tree
Module(children)
at: pathlib
Path()
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
+ @dataclass(unsafe_hash=True)
+ class PyDefinition:
+ full_name: PyFullName
+ module: ModuleName
+ file: Path
+ start_pos: tuple[int, int]
+ end_pos: tuple[int, int]
+
===========changed ref 1===========
# module: coeditor.ctx_change_encoder
@dataclass
class JediUsageAnalysis:
follow_imports: bool = True
+ only_same_project_usages: bool = False
- only_same_project_usages: bool = True
===========changed ref 2===========
# module: coeditor.ctx_change_encoder
@dataclass
class LineUsageAnalysis:
+ line2usages: Mapping[int, set[PyDefinition]]
- line2usages: dict[int, set[PyFullName]]
===========changed ref 3===========
# module: coeditor.ctx_change_encoder
+ @dataclass(unsafe_hash=True)
+ class PyDefinition:
+ @staticmethod
+ def from_signatures(
+ name: classes.BaseName, project: Path | None = None
+ ) -> Iterable["PyDefinition"]:
+ if name.in_builtin_module():
+ return
+ for sig in name.get_signatures():
+ if (
+ not sig.in_builtin_module()
+ and (full_name := sig.full_name)
+ and (file := sig.module_path)
+ and (project in file.parents)
+ and (module := sig.module_name)
+ and (start_pos := sig.get_definition_start_position())
+ and (end_pos := sig.get_definition_end_position())
+ ):
+ full_name = PyFullName(full_name)
+ yield PyDefinition(full_name, module, file, start_pos, end_pos)
+
===========changed ref 4===========
# module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def encode_change(
self,
pchange: JProjectChange,
mod2usages: Mapping[ModuleName, LineUsageAnalysis],
module_order: Sequence[ModuleName],
) -> Iterable[CtxCodeChangeProblem]:
def _get_relevant(span: ChangedSpan):
if isinstance(span.change, Added):
# nothing to analyze
return []
path = span.parent_scopes[-1].earlier().path
line_usages = mod2usages[path.module]
+ all_used = set[PyDefinition]()
- all_used = set[PyFullName]()
l_start, l_end = span.line_range
for l in range(l_start, l_end + 1):
+ for pydef in line_usages.line2usages.get(l, set()):
+ if (
+ pydef.module == path.module
+ and l_start <= pydef.start_pos[0] <= l_end
+ ):
+ # skip self references
+ print(f"Skip: {pydef}")
+ continue
+ all_used.add(pydef)
- all_used.update(line_usages.line2usages.get(l, tuple()))
result = list[tuple[ProjectPath, str]]()
for used in all_used:
+ result.append((ProjectPath(used.full_name, ""), str(used)))
- result.append((ProjectPath("?", used), used))
return result
sorted_cspans = list[ChangedSpan]()
for m in module_order:
if (mchange := pchange.changed.get(m)) is None:
continue
for span in mchange.changed.values():
if span.change.as_char() == Modified.as_char():
yield CtxCodeChangeProblem(
span,
relevant_changes=sorted_cspans.copy(),
relevant_unchanged=</s>
===========changed ref 5===========
# module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def encode_change(
self,
pchange: JProjectChange,
mod2usages: Mapping[ModuleName, LineUsageAnalysis],
module_order: Sequence[ModuleName],
) -> Iterable[CtxCodeChangeProblem]:
# offset: 1
<s> yield CtxCodeChangeProblem(
span,
relevant_changes=sorted_cspans.copy(),
relevant_unchanged=_get_relevant(span),
)
sorted_cspans.append(span)
|
coeditor.code_change/_edits_from_commit_history | Modified | temp-1 | 3fc7535603679d696adc71d9db9ffc11f0ba700e | Analyzing only changed lines to speed up. | <0>:<add> checkout_commit(commit_next.hash)
| # module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
<s>_path = RelPath(path.relative_to(project))
match path_change:
case Added():
mod = parse_module(path)
new_path2module[rel_path] = mod
changed[mod.mname] = JModuleChange.from_modules(Added(mod))
case Deleted():
mod = new_path2module.pop(rel_path)
changed[mod.mname] = JModuleChange.from_modules(Deleted(mod))
case Modified(path1, path2):
assert path1 == path2
mod_old = new_path2module[rel_path]
new_path2module[rel_path] = mod_new = parse_module(path)
changed[mod_new.mname] = JModuleChange.from_modules(
Modified(mod_old, mod_new)
)
with _tlogger.timed("post_edit_analysis"):
post_analysis = change_encoder.post_edit_analysis(
proj,
new_path2module,
+ changed,
- path_changes,
)
+
+ # now go backwards in time to perform pre-edit analysis
+ checkout_commit(commit_now.hash)
+ with _tlogger.timed("pre_edit_analysis"):
+ pre_analysis = change_encoder.pre_edit_analysis(
+ proj,
+ path2module,
+ changed,
+ )
<0>
pchange = JProjectChange(changed, commit_next)
with _tlogger.timed("encode_change"):
encs = change_encoder.encode_change(pchange, pre_analysis, post_analysis)
yield from encs
commit_now = commit_next
path2module = new_path2module
| ===========above chunk 0===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: -1
<s>) == 2:
tag, path = segs
if not is_src(path):
continue
if tag.endswith("A"):
path_changes.append(Added(path))
elif tag.endswith("D"):
path_changes.append(Deleted(path))
if tag.endswith("M"):
path_changes.append(Modified(path, path))
elif len(segs) == 3:
tag, path1, path2 = segs
assert tag.startswith("R")
if not is_src(path1) or not is_src(path2):
continue
path_changes.append(Deleted(path1))
path_changes.append(Added(path2))
- with _tlogger.timed("pre_edit_analysis"):
- pre_analysis = change_encoder.pre_edit_analysis(
- proj,
- path2module,
- path_changes,
- )
+ checkout_commit(commit_next.hash)
- # check out commit_next
- with _tlogger.timed("checkout"):
- subprocess.run(
- ["git", "checkout", commit_next.hash],
- cwd=project,
- capture_output=True,
- check=True,
- )
proj = jedi.Project(path=project, added_sys_path=[project / "src"])
new_path2module = path2module.copy()
changed = dict[ModuleName, JModuleChange]()
for path_change in path_changes:
path = project / path_change.earlier()
rel_path = RelPath(path.relative_to(project))
match path_change:
case Added():
mod =</s>
===========above chunk 1===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: -2
<s>logger.timed("checkout"):
- subprocess.run(
- ["git", "checkout", "-f", commit_now.hash],
- cwd=project,
- capture_output=True,
- check=True,
- )
+ checkout_commit(commit_now.hash, force=True)
proj = jedi.Project(path=project, added_sys_path=[project / "src"])
# now we can get the first project state, although this not needed for now
# but we'll use it later for pre-edit analysis
path2module = {
RelPath(f): parse_module(project / f) for f in get_python_files(project)
}
def is_src(path_s: str) -> bool:
path = Path(path_s)
return path.suffix == ".py" and all(p not in ignore_dirs for p in path.parts)
future_commits = list(reversed(history[:-1]))
for commit_next in tqdm(
future_commits, smoothing=0, desc="processing commits", disable=silent
):
# get changed files
changed_files = run_command(
["git", "diff", commit_now.hash, commit_next.hash, "--name-status"],
cwd=project,
).splitlines()
path_changes = list[Change[str]]()
for line in changed_files:
segs = line.split("\t")
if len(segs) == 2:
tag, path = segs
if not is_src(path):
continue
if tag.ends</s>
===========above chunk 2===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: -3
<s>)
mcontext = s._get_module_context()
assert isinstance(mcontext, ModuleContext)
mname = cast(str, mcontext.py__name__())
if mname.startswith("src."):
e = ValueError(f"Bad module name: {mname}")
files = list(project.iterdir())
print_err(f"project: {proj}", file=sys.stderr)
print_err(f"files in root: {files}", file=sys.stderr)
raise e
m = copy.deepcopy(s._module_node) # needed due to reusing
assert isinstance(m, ptree.Module)
# mname = PythonProject.rel_path_to_module_name(path.relative_to(proj.path))
# m = parso.parse(path.read_text())
return JModule(mname, m)
+ def checkout_commit(commit_hash: str, force: bool = False):
+ with _tlogger.timed("checkout"):
+ subprocess.run(
+ ["git", "checkout", "-f", commit_hash],
+ cwd=project,
+ capture_output=True,
+ check=True,
+ )
- # turn this off so we don't have to deep copy the Modules
- # jedi.settings.fast_parser = False
- # Update: Have to use deep copy for now due to a bug in jedi: https://github.com/davidhalter/jedi/issues/1888
# checkout to the first commit
commit_now = history[-1]
- with</s>
===========above chunk 3===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: -4
def parse_module(path: Path):
with _tlogger.timed("parse_module"):
s = jedi.Script(path=path, project</s> |
coeditor.ctx_change_encoder/PyDefinition.from_signatures | Modified | temp-1 | 3fc7535603679d696adc71d9db9ffc11f0ba700e | Analyzing only changed lines to speed up. | <0>:<add> yield PyDefinition(full_name, import_module, start_pos, end_pos)
| # module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
@staticmethod
- def from_signatures(
- name: classes.BaseName, project: Path | None = None
- ) -> Iterable["PyDefinition"]:
+ def from_signatures(name: classes.BaseName) -> Iterable["PyDefinition"]:
+ cast(classes.Name, name).is_definition()
+ if (
+ not name.in_builtin_module()
- if name.in_builtin_module():
- return
- for sig in name.get_signatures():
- if (
- not sig.in_builtin_module()
+ and (full_name := name.full_name)
- and (full_name := sig.full_name)
- and (file := sig.module_path)
- and (project in file.parents)
+ and (import_module := name.module_name)
- and (module := sig.module_name)
+ and (start_pos := name.get_definition_start_position())
- and (start_pos := sig.get_definition_start_position())
+ and (end_pos := name.get_definition_end_position())
- and (end_pos := sig.get_definition_end_position())
+ ):
- ):
+ full_name = PyFullName(full_name)
- full_name = PyFullName(full_name)
- yield PyDefinition(full_name, module, file, start_pos, end_pos)
<0>
| ===========unchanged ref 0===========
at: coeditor.ctx_change_encoder
PyFullName = NewType("PyPathStr", str)
PyDefinition(full_name: PyFullName, import_module: ModuleName, start_pos: tuple[int, int], end_pos: tuple[int, int])
at: coeditor.ctx_change_encoder.PyDefinition
full_name: PyFullName
import_module: ModuleName
at: dataclasses
dataclass(_cls: Type[_T]) -> Type[_T]
dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]]
dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]
at: jedi.api.classes
BaseName(inference_state, name)
Name(inference_state, definition)
at: jedi.api.classes.BaseName
_mapping = {
'posixpath': 'os.path',
'riscospath': 'os.path',
'ntpath': 'os.path',
'os2emxpath': 'os.path',
'macpath': 'os.path',
'genericpath': 'os.path',
'posix': 'os',
'_io': 'io',
'_functools': 'functools',
'_collections': 'collections',
'_socket': 'socket',
'_sqlite3': 'sqlite3',
}
_tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in {
'argparse._ActionsContainer': 'argparse.ArgumentParser',
}.items())
in_builtin_module()
get_definition_start_position()
get_definition_end_position()
at: jedi.api.classes.Name
is_definition()
===========unchanged ref 1===========
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
Iterable = _alias(collections.abc.Iterable, 1)
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
+ """Note that the module and positions can be referring to either the import
+ statement or the actual definition."""
+
full_name: PyFullName
+ import_module: ModuleName
- module: ModuleName
- file: Path
start_pos: tuple[int, int]
end_pos: tuple[int, int]
===========changed ref 1===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
def parse_module(path: Path):
with _tlogger.timed("parse_module"):
s = jedi.Script(path=path, project=proj)
mcontext = s._get_module_context()
assert isinstance(mcontext, ModuleContext)
mname = cast(str, mcontext.py__name__())
if mname.startswith("src."):
e = ValueError(f"Bad module name: {mname}")
files = list(project.iterdir())
print_err(f"project: {proj}", file=sys.stderr)
print_err(f"files in root: {files}", file=sys.stderr)
raise e
m = copy.deepcopy(s._module_node) # needed due to reusing
assert isinstance(m, ptree.Module)
# mname = PythonProject.rel_path_to_module_name(path.relative_to(proj.path))
# m = parso.parse(path.read_text())
return JModule(mname, m)
+ def checkout_commit(commit_hash: str, force: bool = False):
+ with _tlogger.timed("checkout"):
+ subprocess.run(
+ ["git", "checkout", "-f", commit_hash],
+ cwd=project,
+ capture_output=True,
+ check=True,
+ )
- # turn this off so we don't have to deep copy the Modules
- # jedi.settings.fast_parser = False
- # Update: Have to use deep copy for now due to a bug in jedi: https://github.com/davidhalter/jedi/issues/1888
# checkout to the first commit
commit_now = history[-1]
- </s>
===========changed ref 2===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: 1
<s>/jedi/issues/1888
# checkout to the first commit
commit_now = history[-1]
- with _tlogger.timed("checkout"):
- subprocess.run(
- ["git", "checkout", "-f", commit_now.hash],
- cwd=project,
- capture_output=True,
- check=True,
- )
+ checkout_commit(commit_now.hash, force=True)
proj = jedi.Project(path=project, added_sys_path=[project / "src"])
# now we can get the first project state, although this not needed for now
# but we'll use it later for pre-edit analysis
path2module = {
RelPath(f): parse_module(project / f) for f in get_python_files(project)
}
def is_src(path_s: str) -> bool:
path = Path(path_s)
return path.suffix == ".py" and all(p not in ignore_dirs for p in path.parts)
future_commits = list(reversed(history[:-1]))
for commit_next in tqdm(
future_commits, smoothing=0, desc="processing commits", disable=silent
):
# get changed files
changed_files = run_command(
["git", "diff", commit_now.hash, commit_next.hash, "--name-status"],
cwd=project,
).splitlines()
path_changes = list[Change[str]]()
for line in changed_files:
segs = line.split("\t")
if len</s> |
coeditor.ctx_change_encoder/CtxCodeChangeProblemGenerator.pre_edit_analysis | Modified | temp-1 | 3fc7535603679d696adc71d9db9ffc11f0ba700e | Analyzing only changed lines to speed up. | <0>:<add> result[mname] = line_usages
| # module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def pre_edit_analysis(
self,
project: jedi.Project,
modules: Mapping[RelPath, JModule],
+ changes: Mapping[ModuleName, JModuleChange],
- file_changes: Sequence[Change[str]],
) -> Mapping[ModuleName, LineUsageAnalysis]:
<s>path)
result = dict[ModuleName, LineUsageAnalysis]()
+
+ src_map = {m.mname: f for f, m in modules.items()}
+ for mname, mchange in changes.items():
- for change in file_changes:
+ if not isinstance(mchange.module_change, Modified):
- if not isinstance(change, Modified):
continue
+
+ lines_to_analyze = set[int]()
+ for span in mchange.changed.values():
+ if span.change is Added:
+ continue
+ start, end = span.line_range
+ lines_to_analyze.update(range(start, end + 1))
+
+ mod_path = src_map[mname]
+ assert (
+ src_file := project.path / mod_path
+ ).exists(), f"src file missing: {src_file}"
- mod_path = RelPath(Path(change.before))
- jmod = modules[mod_path]
- assert (project.path / mod_path).exists()
+ script = jedi.Script(path=src_file, project=project)
- script = jedi.Script(path=project.path / mod_path, project=project)
+ line_usages = self.analysis.get_line_usages(
- line_usages = self.analysis.get_module_usages(
+ script, project.path, lines_to_analyze, silent=True
- script, project.path, silent=True
)
- result[jmod.mname] = line_usages
<0> return result
| ===========above chunk 0===========
# module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def pre_edit_analysis(
self,
project: jedi.Project,
modules: Mapping[RelPath, JModule],
+ changes: Mapping[ModuleName, JModuleChange],
- file_changes: Sequence[Change[str]],
) -> Mapping[ModuleName, LineUsageAnalysis]:
# offset: -1
"Return the definition usages of each line."
# proot = Path(project._path)
result = dict[ModuleName, LineUsageAnalysis]()
+
+ src_map = {m.mname:</s>
===========unchanged ref 0===========
at: coeditor.common
RelPath = NewType("RelPath", Path)
at: coeditor.ctx_change_encoder
LineUsageAnalysis(line2usages: Mapping[int, set[PyDefinition]])
at: spot.static_analysis
ModuleName = str
at: typing
Mapping = _alias(collections.abc.Mapping, 2)
at: typing.Mapping
items() -> AbstractSet[Tuple[_KT, _VT_co]]
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
+ """Note that the module and positions can be referring to either the import
+ statement or the actual definition."""
+
full_name: PyFullName
+ import_module: ModuleName
- module: ModuleName
- file: Path
start_pos: tuple[int, int]
end_pos: tuple[int, int]
===========changed ref 1===========
# module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
@staticmethod
- def from_signatures(
- name: classes.BaseName, project: Path | None = None
- ) -> Iterable["PyDefinition"]:
+ def from_signatures(name: classes.BaseName) -> Iterable["PyDefinition"]:
+ cast(classes.Name, name).is_definition()
+ if (
+ not name.in_builtin_module()
- if name.in_builtin_module():
- return
- for sig in name.get_signatures():
- if (
- not sig.in_builtin_module()
+ and (full_name := name.full_name)
- and (full_name := sig.full_name)
- and (file := sig.module_path)
- and (project in file.parents)
+ and (import_module := name.module_name)
- and (module := sig.module_name)
+ and (start_pos := name.get_definition_start_position())
- and (start_pos := sig.get_definition_start_position())
+ and (end_pos := name.get_definition_end_position())
- and (end_pos := sig.get_definition_end_position())
+ ):
- ):
+ full_name = PyFullName(full_name)
- full_name = PyFullName(full_name)
+ yield PyDefinition(full_name, import_module, start_pos, end_pos)
- yield PyDefinition(full_name, module, file, start_pos, end_pos)
===========changed ref 2===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
def parse_module(path: Path):
with _tlogger.timed("parse_module"):
s = jedi.Script(path=path, project=proj)
mcontext = s._get_module_context()
assert isinstance(mcontext, ModuleContext)
mname = cast(str, mcontext.py__name__())
if mname.startswith("src."):
e = ValueError(f"Bad module name: {mname}")
files = list(project.iterdir())
print_err(f"project: {proj}", file=sys.stderr)
print_err(f"files in root: {files}", file=sys.stderr)
raise e
m = copy.deepcopy(s._module_node) # needed due to reusing
assert isinstance(m, ptree.Module)
# mname = PythonProject.rel_path_to_module_name(path.relative_to(proj.path))
# m = parso.parse(path.read_text())
return JModule(mname, m)
+ def checkout_commit(commit_hash: str, force: bool = False):
+ with _tlogger.timed("checkout"):
+ subprocess.run(
+ ["git", "checkout", "-f", commit_hash],
+ cwd=project,
+ capture_output=True,
+ check=True,
+ )
- # turn this off so we don't have to deep copy the Modules
- # jedi.settings.fast_parser = False
- # Update: Have to use deep copy for now due to a bug in jedi: https://github.com/davidhalter/jedi/issues/1888
# checkout to the first commit
commit_now = history[-1]
- </s>
===========changed ref 3===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: 1
<s>/jedi/issues/1888
# checkout to the first commit
commit_now = history[-1]
- with _tlogger.timed("checkout"):
- subprocess.run(
- ["git", "checkout", "-f", commit_now.hash],
- cwd=project,
- capture_output=True,
- check=True,
- )
+ checkout_commit(commit_now.hash, force=True)
proj = jedi.Project(path=project, added_sys_path=[project / "src"])
# now we can get the first project state, although this not needed for now
# but we'll use it later for pre-edit analysis
path2module = {
RelPath(f): parse_module(project / f) for f in get_python_files(project)
}
def is_src(path_s: str) -> bool:
path = Path(path_s)
return path.suffix == ".py" and all(p not in ignore_dirs for p in path.parts)
future_commits = list(reversed(history[:-1]))
for commit_next in tqdm(
future_commits, smoothing=0, desc="processing commits", disable=silent
):
# get changed files
changed_files = run_command(
["git", "diff", commit_now.hash, commit_next.hash, "--name-status"],
cwd=project,
).splitlines()
path_changes = list[Change[str]]()
for line in changed_files:
segs = line.split("\t")
if len</s> |
coeditor.code_change/ChangeScope.all_code | Modified | temp-1 | b2f78bf15287dca9f1312cdd7720e6e9175fdeef | Fix line ranges. Improve analysis and add tests. | <0>:<add> return self.header_code + self.spans_code
| # module: coeditor.code_change
@dataclass
class ChangeScope:
@cached_property
def all_code(self) -> str:
- return f"{self.header_code}\n{self.spans_code}"
<0>
| ===========changed ref 0===========
# module: coeditor.code_change
+ def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
+ if not can_be_empty and start >= end:
+ raise ValueError(f"Bad line range: {start=}, {end=}")
+ return _LineRange((start, end))
+
===========changed ref 1===========
# module: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
PyNode = ptree.PythonBaseNode | ptree.PythonNode
+ _LineRange = NewType("LineRange", tuple[int, int])
_tlogger = TimeLogger()
===========changed ref 2===========
# module: coeditor.code_change
+ def _strip_empty_lines(s: str):
+ s1 = s.lstrip("\n")
+ s2 = s1.rstrip("\n")
+ e_lines_left = len(s) - len(s1)
+ e_lines_right = len(s1) - len(s2)
+ return s2, e_lines_left, e_lines_right
+
===========changed ref 3===========
+ # module: tests.coeditor.testcases.usages
+
+
===========changed ref 4===========
+ # module: tests.coeditor.testcases.defs
+
+
===========changed ref 5===========
+ # module: tests.coeditor.testcases.usages
+ def get_named_changes(*args):
+ raise NotImplementedError
+
===========changed ref 6===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ def iter_imports(self, tree):
+ raise NotImplementedError
+
===========changed ref 7===========
+ # module: tests.coeditor.testcases.usages
+ get_modified_spans = as_any(None)
+
===========changed ref 8===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ @cached_property
+ def spans_code(self) -> str:
+ return "\n".join(s.code for s in self.spans)
+
===========changed ref 9===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ def _to_scope(self) -> ChangeScope:
+ return ChangeScope.from_tree(ProjectPath(self.mname, ""), self.tree)
+
===========changed ref 10===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ "A light wrapper around a jedi module."
+ mname: ModuleName
+ tree: ptree.Module
+
===========changed ref 11===========
+ # module: tests.coeditor.testcases.defs
+ ScopeTree = ptree.Function | ptree.Class | ptree.Module
+ ChangedSpan = NewType("ChangedSpan", str)
+
===========changed ref 12===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ """
+ A change scope is a python module, non-hidden function, or a non-hidden class, or a python module.
+ - functions and classes that are inside a parent function are considered hidden.
+ """
+
+ path: ProjectPath
+ tree: ScopeTree
+ spans: Sequence
+ subscopes: Mapping[ProjectPath, Self]
+
===========changed ref 13===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ @staticmethod
+ def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
+ spans = []
+ subscopes = dict()
+ scope = ChangeScope(path, tree, spans, subscopes)
+ assert isinstance(tree, ScopeTree)
+ is_func = isinstance(tree, ptree.Function)
+
+ current_stmts = []
+ content = (
+ tree.children
+ if isinstance(tree, ptree.Module)
+ else cast(ptree.PythonNode, tree.get_suite()).children
+ )
+ raise NotImplementedError
+
===========changed ref 14===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ @cached_property
+ def imported_names(self):
+ names = set[ptree.Name]()
+ for stmt in self.iter_imports(self.tree):
+ if isinstance(stmt, ptree.ImportFrom):
+ for n in stmt.get_from_names():
+ assert isinstance(n, ptree.Name)
+ names.add(n)
+ elif isinstance(stmt, ptree.ImportName):
+ for n in stmt.get_defined_names():
+ assert isinstance(n, ptree.Name)
+ names.add(n)
+ return names
+
===========changed ref 15===========
+ # module: tests.coeditor.testcases.usages
+ def recurse(scope_change: Change[ChangeScope], parent_changes) -> Iterable[ChangedSpan]:
+ parent_changes = (*parent_changes, scope_change)
+ match scope_change:
+ case Modified(old_scope, new_scope):
+ # compute statement differences
+ yield from get_modified_spans(old_scope, new_scope, parent_changes)
+ for sub_change in get_named_changes(
+ old_scope.subscopes, new_scope.subscopes
+ ).values():
+ yield from recurse(sub_change, parent_changes)
+ case Added(scope) | Deleted(scope):
+ for span in scope.spans:
+ code_change = scope_change.new_value(span.code)
+ yield ChangedSpan(
+ code_change,
+ parent_changes,
+ span.line_range,
+ )
+ for s in scope.subscopes.values():
+ s_change = scope_change.new_value(s)
+ yield from recurse(s_change, parent_changes)
+ |
coeditor.code_change/_edits_from_commit_history | Modified | temp-1 | b2f78bf15287dca9f1312cdd7720e6e9175fdeef | Fix line ranges. Improve analysis and add tests. | <0>:<add> pchange = JProjectChange(changed, modules_mod, commit_next)
| # module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
<s>change:
case Added():
mod = parse_module(path)
new_path2module[rel_path] = mod
changed[mod.mname] = JModuleChange.from_modules(Added(mod))
case Deleted():
mod = new_path2module.pop(rel_path)
changed[mod.mname] = JModuleChange.from_modules(Deleted(mod))
case Modified(path1, path2):
assert path1 == path2
mod_old = new_path2module[rel_path]
new_path2module[rel_path] = mod_new = parse_module(path)
changed[mod_new.mname] = JModuleChange.from_modules(
Modified(mod_old, mod_new)
)
with _tlogger.timed("post_edit_analysis"):
post_analysis = change_encoder.post_edit_analysis(
proj,
new_path2module,
changed,
)
# now go backwards in time to perform pre-edit analysis
checkout_commit(commit_now.hash)
with _tlogger.timed("pre_edit_analysis"):
pre_analysis = change_encoder.pre_edit_analysis(
proj,
path2module,
changed,
)
checkout_commit(commit_next.hash)
+ modules_mod = Modified(path2module.values(), new_path2module.values())
- pchange = JProjectChange(changed, commit_next)
<0>
with _tlogger.timed("encode_change"):
encs = change_encoder.encode_change(pchange, pre_analysis, post_analysis)
yield from encs
commit_now = commit_next
path2module = new_path2module
| ===========above chunk 0===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: -1
<s>0, desc="processing commits", disable=silent
):
# get changed files
changed_files = run_command(
["git", "diff", commit_now.hash, commit_next.hash, "--name-status"],
cwd=project,
).splitlines()
path_changes = list[Change[str]]()
for line in changed_files:
segs = line.split("\t")
if len(segs) == 2:
tag, path = segs
if not is_src(path):
continue
if tag.endswith("A"):
path_changes.append(Added(path))
elif tag.endswith("D"):
path_changes.append(Deleted(path))
if tag.endswith("M"):
path_changes.append(Modified(path, path))
elif len(segs) == 3:
tag, path1, path2 = segs
assert tag.startswith("R")
if not is_src(path1) or not is_src(path2):
continue
path_changes.append(Deleted(path1))
path_changes.append(Added(path2))
checkout_commit(commit_next.hash)
proj = jedi.Project(path=project, added_sys_path=[project / "src"])
new_path2module = path2module.copy()
changed = dict[ModuleName, JModuleChange]()
for path_change in path_changes:
path = project / path_change.earlier()
rel_path = RelPath(path.relative_to(project))
match path_change:
case Added():
mod = parse_module(path)
new_path2module[rel_path] =</s>
===========above chunk 1===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: -2
<s> # m = parso.parse(path.read_text())
return JModule(mname, m)
def checkout_commit(commit_hash: str, force: bool = False):
with _tlogger.timed("checkout"):
subprocess.run(
["git", "checkout", "-f", commit_hash],
cwd=project,
capture_output=True,
check=True,
)
# checkout to the first commit
commit_now = history[-1]
checkout_commit(commit_now.hash, force=True)
proj = jedi.Project(path=project, added_sys_path=[project / "src"])
# now we can get the first project state, although this not needed for now
# but we'll use it later for pre-edit analysis
path2module = {
+ RelPath(f): parse_module(project / f)
+ for f in tqdm(
+ get_python_files(project), desc="building initial project", disable=silent
+ )
- RelPath(f): parse_module(project / f) for f in get_python_files(project)
}
def is_src(path_s: str) -> bool:
path = Path(path_s)
return path.suffix == ".py" and all(p not in ignore_dirs for p in path.parts)
future_commits = list(reversed(history[:-1]))
for commit_next in tqdm(
future_commits, smoothing=0, desc="processing commits", disable=silent
):
# get changed files
changed_files = run_command(</s>
===========above chunk 2===========
# module: coeditor.code_change
def _edits_from_commit_history(
project: Path,
history: Sequence[CommitInfo],
change_encoder: ProjectChangeProcessor[TEnc],
ignore_dirs: set[str],
silent: bool,
) -> Iterable[TEnc]:
# offset: -3
def parse_module(path: Path):
with _tlogger.timed("parse_module"):
s = jedi.Script(path=path, project=proj)
mcontext = s._get_module_context()
assert isinstance(mcontext, ModuleContext)
mname = cast(str, mcontext.py__name__())
if mname.startswith("src."):
e = ValueError(f"Bad module name: {mname}")
files = list(project.iterdir())
print_err(f"project: {proj}", file=sys.stderr)
print_err(f"files in root: {files}", file=sys.stderr)
raise e
m = copy.deepcopy(s._module_node) # needed due to reusing
assert isinstance(m, ptree.Module)
# mname = PythonProject.rel_path_to_module_name(path.relative_to(proj.path))</s>
===========unchanged ref 0===========
at: coeditor._utils.TimeLogger
times: dict[str, list[float]] = field(default_factory=dict)
timed(name: str)
at: coeditor.code_change
_tlogger = TimeLogger()
JModule(mname: ModuleName, tree: ptree.Module)
JModuleChange(module_change: Change[JModule], changed: Mapping[ProjectPath, ChangedSpan])
get_python_files(project: Path)
DefaultIgnoreDirs = {".venv", ".mypy_cache", ".git", "venv", "build"}
TEnc = TypeVar("TEnc", covariant=True)
ProjectChangeProcessor()
NoProcessing()
at: coeditor.code_change.JModuleChange
module_change: Change[JModule]
changed: Mapping[ProjectPath, ChangedSpan]
from_modules(module_change: Change[JModule])
at: coeditor.common
RelPath = NewType("RelPath", Path)
run_command(args: Sequence[str], cwd: str | Path) -> str
print_err(*, sep: Optional[str]=..., end: Optional[str]=..., flush: bool=...) -> None
at: copy
deepcopy(x: _T, memo: Optional[Dict[int, Any]]=..., _nil: Any=...) -> _T
at: jedi.api
Script(code=None, *, path=None, environment=None, project=None)
at: jedi.api.Script
_get_module_context()
at: jedi.api.Script.__init__
self._module_node, code = self._inference_state.parse_and_get_code(
code=code,
path=self.path,
use_latest_grammar=path and path.suffix == '.pyi',
cache=False, # No disk cache, because the current script often changes.
diff_cache=settings.fast_parser,
cache_path=settings.cache_directory,
)
|
coeditor.ctx_change_encoder/CtxCodeChangeProblemGenerator.__init__ | Modified | temp-1 | b2f78bf15287dca9f1312cdd7720e6e9175fdeef | Fix line ranges. Improve analysis and add tests. | <0>:<add> analysis = JediUsageAnalyzer()
| # module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
+ def __init__(self, analysis: "JediUsageAnalyzer | None"):
- def __init__(self, analysis: "JediUsageAnalysis | None"):
if analysis is None:
- analysis = JediUsageAnalysis()
<0> self.analysis = analysis
| ===========unchanged ref 0===========
at: coeditor.ctx_change_encoder
CtxCodeChangeProblem(span: ChangedSpan, relevant_changes: list[ChangedSpan], relevant_unchanged: list[tuple[ProjectPath, str]])
JediUsageAnalyzer(follow_imports: bool=True)
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
- jedi.cache.clear_time_caches = lambda: None
-
===========changed ref 1===========
+ # module: tests.coeditor.test_analysis
+
+
===========changed ref 2===========
+ # module: tests.coeditor.testcases.usages
+
+
===========changed ref 3===========
+ # module: tests.coeditor.testcases.defs
+
+
===========changed ref 4===========
+ # module: tests.coeditor.testcases.usages
+ def get_named_changes(*args):
+ raise NotImplementedError
+
===========changed ref 5===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ def iter_imports(self, tree):
+ raise NotImplementedError
+
===========changed ref 6===========
+ # module: tests.coeditor.testcases.usages
+ get_modified_spans = as_any(None)
+
===========changed ref 7===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ @cached_property
+ def spans_code(self) -> str:
+ return "\n".join(s.code for s in self.spans)
+
===========changed ref 8===========
+ # module: tests.coeditor.test_analysis
+ testcase_root = proj_root() / "tests" / "coeditor" / "testcases"
+
===========changed ref 9===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ def _to_scope(self) -> ChangeScope:
+ return ChangeScope.from_tree(ProjectPath(self.mname, ""), self.tree)
+
===========changed ref 10===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ "A light wrapper around a jedi module."
+ mname: ModuleName
+ tree: ptree.Module
+
===========changed ref 11===========
+ # module: tests.coeditor.testcases.defs
+ ScopeTree = ptree.Function | ptree.Class | ptree.Module
+ ChangedSpan = NewType("ChangedSpan", str)
+
===========changed ref 12===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@cached_property
def all_code(self) -> str:
+ return self.header_code + self.spans_code
- return f"{self.header_code}\n{self.spans_code}"
===========changed ref 13===========
# module: coeditor.code_change
@dataclass
class JProjectChange:
changed: Mapping[ModuleName, JModuleChange]
+ all_modules: Modified[Collection[JModule]]
commit_info: "CommitInfo | None"
===========changed ref 14===========
# module: coeditor.code_change
@dataclass
class ChangedSpan:
+ @property
+ def header_line_range(self) -> _LineRange:
+ parent_scope = self.parent_scopes[-1].earlier()
+ hrange = parent_scope.header_line_range
+ return hrange
+
===========changed ref 15===========
# module: coeditor.code_change
+ def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
+ if not can_be_empty and start >= end:
+ raise ValueError(f"Bad line range: {start=}, {end=}")
+ return _LineRange((start, end))
+
===========changed ref 16===========
+ # module: tests.coeditor.test_analysis
+ def assert_has_usages(defs: Collection[PyDefinition], *full_names: str):
+ nameset = list(d.full_name for d in defs)
+ for name in full_names:
+ if PyFullName(name) not in nameset:
+ raise AssertionError(f"{name} not in {nameset}")
+
===========changed ref 17===========
+ # module: tests.coeditor.test_analysis
+ def assert_no_usages(defs: Collection[PyDefinition], *full_names: str):
+ nameset = list(d.full_name for d in defs)
+ for name in full_names:
+ if PyFullName(name) in nameset:
+ raise AssertionError(f"{name} should not be in {nameset}")
+
===========changed ref 18===========
# module: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
PyNode = ptree.PythonBaseNode | ptree.PythonNode
+ _LineRange = NewType("LineRange", tuple[int, int])
_tlogger = TimeLogger()
===========changed ref 19===========
# module: coeditor.code_change
@dataclass
class ChangedSpan:
"Represents the changes made to a statement span."
change: Change[str]
parent_scopes: Sequence[Change[ChangeScope]]
- line_range: tuple[int, int]
- old_statements: Sequence[PyNode]
+ line_range: _LineRange
===========changed ref 20===========
# module: coeditor.code_change
+ def _strip_empty_lines(s: str):
+ s1 = s.lstrip("\n")
+ s2 = s1.rstrip("\n")
+ e_lines_left = len(s) - len(s1)
+ e_lines_right = len(s1) - len(s2)
+ return s2, e_lines_left, e_lines_right
+
===========changed ref 21===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ """
+ A change scope is a python module, non-hidden function, or a non-hidden class, or a python module.
+ - functions and classes that are inside a parent function are considered hidden.
+ """
+
+ path: ProjectPath
+ tree: ScopeTree
+ spans: Sequence
+ subscopes: Mapping[ProjectPath, Self]
+
===========changed ref 22===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ @staticmethod
+ def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
+ spans = []
+ subscopes = dict()
+ scope = ChangeScope(path, tree, spans, subscopes)
+ assert isinstance(tree, ScopeTree)
+ is_func = isinstance(tree, ptree.Function)
+
+ current_stmts = []
+ content = (
+ tree.children
+ if isinstance(tree, ptree.Module)
+ else cast(ptree.PythonNode, tree.get_suite()).children
+ )
+ raise NotImplementedError
+
===========changed ref 23===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ @cached_property
+ def imported_names(self):
+ names = set[ptree.Name]()
+ for stmt in self.iter_imports(self.tree):
+ if isinstance(stmt, ptree.ImportFrom):
+ for n in stmt.get_from_names():
+ assert isinstance(n, ptree.Name)
+ names.add(n)
+ elif isinstance(stmt, ptree.ImportName):
+ for n in stmt.get_defined_names():
+ assert isinstance(n, ptree.Name)
+ names.add(n)
+ return names
+ |
coeditor.ctx_change_encoder/CtxCodeChangeProblemGenerator.pre_edit_analysis | Modified | temp-1 | b2f78bf15287dca9f1312cdd7720e6e9175fdeef | Fix line ranges. Improve analysis and add tests. | <0>:<add> lines_to_analyze.update(range(*span.header_line_range))
| # module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def pre_edit_analysis(
self,
project: jedi.Project,
modules: Mapping[RelPath, JModule],
changes: Mapping[ModuleName, JModuleChange],
) -> Mapping[ModuleName, LineUsageAnalysis]:
"Return the definition usages of each line."
# proot = Path(project._path)
result = dict[ModuleName, LineUsageAnalysis]()
src_map = {m.mname: f for f, m in modules.items()}
for mname, mchange in changes.items():
if not isinstance(mchange.module_change, Modified):
continue
lines_to_analyze = set[int]()
for span in mchange.changed.values():
if span.change is Added:
continue
- start, end = span.line_range
+ lines_to_analyze.update(range(*span.line_range))
- lines_to_analyze.update(range(start, end + 1))
<0>
mod_path = src_map[mname]
assert (
src_file := project.path / mod_path
).exists(), f"src file missing: {src_file}"
script = jedi.Script(path=src_file, project=project)
line_usages = self.analysis.get_line_usages(
script, project.path, lines_to_analyze, silent=True
)
result[mname] = line_usages
return result
| ===========unchanged ref 0===========
at: coeditor.common
RelPath = NewType("RelPath", Path)
at: coeditor.ctx_change_encoder
LineUsageAnalysis(line2usages: Mapping[int, set[PyDefinition]])
at: coeditor.ctx_change_encoder.CtxCodeChangeProblemGenerator.__init__
analysis = JediUsageAnalyzer()
self.analysis = analysis
at: coeditor.ctx_change_encoder.JediUsageAnalyzer
follow_imports: bool = True
get_line_usages(script: jedi.Script, proj_root: Path, lines_to_analyze: Collection[int], silent: bool=False)
at: jedi.api
Script(code=None, *, path=None, environment=None, project=None)
at: jedi.api.project
Project(path, *, environment_path=None, load_unsafe_extensions=False, sys_path=None, added_sys_path=(), smart_sys_path=True)
at: jedi.api.project.Project
_environment = None
at: pathlib.Path
__slots__ = ()
exists() -> bool
at: spot.static_analysis
ModuleName = str
at: typing
Mapping = _alias(collections.abc.Mapping, 2)
at: typing.Mapping
items() -> AbstractSet[Tuple[_KT, _VT_co]]
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
+ def __init__(self, analysis: "JediUsageAnalyzer | None"):
- def __init__(self, analysis: "JediUsageAnalysis | None"):
if analysis is None:
+ analysis = JediUsageAnalyzer()
- analysis = JediUsageAnalysis()
self.analysis = analysis
===========changed ref 1===========
# module: coeditor.ctx_change_encoder
- jedi.cache.clear_time_caches = lambda: None
-
===========changed ref 2===========
+ # module: tests.coeditor.test_analysis
+
+
===========changed ref 3===========
+ # module: tests.coeditor.testcases.usages
+
+
===========changed ref 4===========
+ # module: tests.coeditor.testcases.defs
+
+
===========changed ref 5===========
+ # module: tests.coeditor.testcases.usages
+ def get_named_changes(*args):
+ raise NotImplementedError
+
===========changed ref 6===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ def iter_imports(self, tree):
+ raise NotImplementedError
+
===========changed ref 7===========
+ # module: tests.coeditor.testcases.usages
+ get_modified_spans = as_any(None)
+
===========changed ref 8===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ @cached_property
+ def spans_code(self) -> str:
+ return "\n".join(s.code for s in self.spans)
+
===========changed ref 9===========
+ # module: tests.coeditor.test_analysis
+ testcase_root = proj_root() / "tests" / "coeditor" / "testcases"
+
===========changed ref 10===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ def _to_scope(self) -> ChangeScope:
+ return ChangeScope.from_tree(ProjectPath(self.mname, ""), self.tree)
+
===========changed ref 11===========
+ # module: tests.coeditor.testcases.usages
+ @dataclass
+ class JModule:
+ "A light wrapper around a jedi module."
+ mname: ModuleName
+ tree: ptree.Module
+
===========changed ref 12===========
+ # module: tests.coeditor.testcases.defs
+ ScopeTree = ptree.Function | ptree.Class | ptree.Module
+ ChangedSpan = NewType("ChangedSpan", str)
+
===========changed ref 13===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@cached_property
def all_code(self) -> str:
+ return self.header_code + self.spans_code
- return f"{self.header_code}\n{self.spans_code}"
===========changed ref 14===========
# module: coeditor.code_change
@dataclass
class JProjectChange:
changed: Mapping[ModuleName, JModuleChange]
+ all_modules: Modified[Collection[JModule]]
commit_info: "CommitInfo | None"
===========changed ref 15===========
# module: coeditor.code_change
@dataclass
class ChangedSpan:
+ @property
+ def header_line_range(self) -> _LineRange:
+ parent_scope = self.parent_scopes[-1].earlier()
+ hrange = parent_scope.header_line_range
+ return hrange
+
===========changed ref 16===========
# module: coeditor.code_change
+ def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
+ if not can_be_empty and start >= end:
+ raise ValueError(f"Bad line range: {start=}, {end=}")
+ return _LineRange((start, end))
+
===========changed ref 17===========
+ # module: tests.coeditor.test_analysis
+ def assert_has_usages(defs: Collection[PyDefinition], *full_names: str):
+ nameset = list(d.full_name for d in defs)
+ for name in full_names:
+ if PyFullName(name) not in nameset:
+ raise AssertionError(f"{name} not in {nameset}")
+
===========changed ref 18===========
+ # module: tests.coeditor.test_analysis
+ def assert_no_usages(defs: Collection[PyDefinition], *full_names: str):
+ nameset = list(d.full_name for d in defs)
+ for name in full_names:
+ if PyFullName(name) in nameset:
+ raise AssertionError(f"{name} should not be in {nameset}")
+
===========changed ref 19===========
# module: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
PyNode = ptree.PythonBaseNode | ptree.PythonNode
+ _LineRange = NewType("LineRange", tuple[int, int])
_tlogger = TimeLogger()
===========changed ref 20===========
# module: coeditor.code_change
@dataclass
class ChangedSpan:
"Represents the changes made to a statement span."
change: Change[str]
parent_scopes: Sequence[Change[ChangeScope]]
- line_range: tuple[int, int]
- old_statements: Sequence[PyNode]
+ line_range: _LineRange
===========changed ref 21===========
# module: coeditor.code_change
+ def _strip_empty_lines(s: str):
+ s1 = s.lstrip("\n")
+ s2 = s1.rstrip("\n")
+ e_lines_left = len(s) - len(s1)
+ e_lines_right = len(s1) - len(s2)
+ return s2, e_lines_left, e_lines_right
+
===========changed ref 22===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ """
+ A change scope is a python module, non-hidden function, or a non-hidden class, or a python module.
+ - functions and classes that are inside a parent function are considered hidden.
+ """
+
+ path: ProjectPath
+ tree: ScopeTree
+ spans: Sequence
+ subscopes: Mapping[ProjectPath, Self]
+
===========changed ref 23===========
+ # module: tests.coeditor.testcases.defs
+ @dataclass
+ class ChangeScope:
+ @staticmethod
+ def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
+ spans = []
+ subscopes = dict()
+ scope = ChangeScope(path, tree, spans, subscopes)
+ assert isinstance(tree, ScopeTree)
+ is_func = isinstance(tree, ptree.Function)
+
+ current_stmts = []
+ content = (
+ tree.children
+ if isinstance(tree, ptree.Module)
+ else cast(ptree.PythonNode, tree.get_suite()).children
+ )
+ raise NotImplementedError
+ |
coeditor.encoding/change_to_line_diffs | Modified | temp-1 | d0fe36e93da8ca33161e524783335898bd47ebbc | - More analysis bug fix. - Encode unchanged using CSpan. | <0>:<add> diffs = compute_line_diffs(splitlines(before), splitlines(after))
| # module: coeditor.encoding
def change_to_line_diffs(change: Change[str]) -> list[str]:
"Encode a change as a token sequence."
match change:
case Modified(before, after):
+ if change.unchanged:
+ diffs = []
+ else:
- diffs = compute_line_diffs(splitlines(before), splitlines(after))
<0> # rearrange_diffs_(diffs)
if not diffs:
# as a special case, `unified_diff` would return an empty when there is no change.
diffs = [" " + l for l in splitlines(before)]
case Added(after):
diffs = ["+" + l for l in splitlines(after)]
case Deleted(before):
diffs = ["-" + l for l in splitlines(before)]
case _:
raise ValueError(f"Invalid change type: {change}.")
return diffs
| ===========unchanged ref 0===========
at: coeditor._utils
compute_line_diffs(before: Sequence[str], after: Sequence[str], keep_explain_lines: bool=False)
at: coeditor.common
splitlines(text: str) -> list[str]
|
tests.coeditor.test_code_change/test_change_scope | Modified | temp-1 | d0fe36e93da8ca33161e524783335898bd47ebbc | - More analysis bug fix. - Encode unchanged using CSpan. | <0>:<add> inner_class_code = scope.subscopes["A"].subscopes["B"].all_code
| # module: tests.coeditor.test_code_change
def test_change_scope():
<s>
assert_str_equal(f1_code, indent(f1_expect, " " * 4))
f2_expect = dedent(
"""\
@annotated
def f2():
return 1
"""
)
+ f2_code = scope.subscopes["f2"].all_code
- f2_code = scope.subscopes[ProjectPath("code1", "f2")].all_code
assert_str_equal(f2_code, f2_expect)
attr1_expect = dedent(
"""\
attr1: int
"""
)
+ attr1_code = scope.subscopes["A"].spans_code
- attr1_code = scope.subscopes[ProjectPath("code1", "A")].spans_code
assert_str_equal(attr1_code, indent(attr1_expect, " " * 4))
method1_expect = dedent(
"""\
@staticmethod
def method1():
return 1
"""
)
- method1_code = (
- scope.subscopes[ProjectPath("code1", "A")]
- .subscopes[ProjectPath("code1", "A.method1")]
- .all_code
- )
+ method1_code = scope.subscopes["A"].subscopes["method1"].all_code
assert_str_equal(method1_code, indent(method1_expect, " " * 4))
inner_attr1_expect = dedent(
"""\
class B:
inner_attr1: int
"""
)
- inner_class_code = (
- scope.subscopes[ProjectPath("code1", "A")]
- .subscopes[ProjectPath("code1", "A.B")]
- .all_code
- )
<0> assert_str_equal(inner_class_code, indent(inner_attr1_expect, " " * 4))
| ===========above chunk 0===========
# module: tests.coeditor.test_code_change
def test_change_scope():
# offset: -1
code1 = dedent(
"""\
import os
x = 1
y = x + 1
def f1():
global x
x *= 5
return x
if __name__ == "__main__":
print(f1() + x)
@annotated
def f2():
return 1
@dataclass
class A:
attr1: int
@staticmethod
def method1():
return 1
class B:
inner_attr1: int
"""
)
mod_tree = code_to_module(code1)
scope = ChangeScope.from_tree(ProjectPath("code1", ""), mod_tree)
global_spans = [
dedent(
"""\
x = 1
y = x + 1
"""
),
dedent(
"""\
if __name__ == "__main__":
print(f1() + x)
"""
),
]
for i, code in enumerate(global_spans):
assert_str_equal(scope.spans[i].code, code)
f1_expect = dedent(
"""\
global x
x *= 5
return x
"""
)
+ f1_code = scope.subscopes["f1"].spans_code
- f1_code = scope.subscopes[ProjectPath("code1", "f1")].spans_code
assert_str_equal(f1_code, indent(f1_expect, " " * 4))
f2</s>
===========unchanged ref 0===========
at: tests.coeditor.test_code_change.TestChangedSpan
scope1 = ChangeScope.from_tree(ProjectPath("code1", ""), code_to_module(code1))
at: textwrap
indent(text: str, prefix: str, predicate: Optional[Callable[[str], bool]]=...) -> str
===========changed ref 0===========
# module: coeditor.encoding
def change_to_line_diffs(change: Change[str]) -> list[str]:
"Encode a change as a token sequence."
match change:
case Modified(before, after):
+ if change.unchanged:
+ diffs = []
+ else:
+ diffs = compute_line_diffs(splitlines(before), splitlines(after))
- diffs = compute_line_diffs(splitlines(before), splitlines(after))
# rearrange_diffs_(diffs)
if not diffs:
# as a special case, `unified_diff` would return an empty when there is no change.
diffs = [" " + l for l in splitlines(before)]
case Added(after):
diffs = ["+" + l for l in splitlines(after)]
case Deleted(before):
diffs = ["-" + l for l in splitlines(before)]
case _:
raise ValueError(f"Invalid change type: {change}.")
return diffs
|
coeditor.code_change/ChangeScope.from_tree | Modified | temp-1 | d0fe36e93da8ca33161e524783335898bd47ebbc | - More analysis bug fix. - Encode unchanged using CSpan. | <0>:<add> subscopes[name] = subscope
| # module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
spans = []
subscopes = dict()
+ scope = ChangeScope(path, tree, spans, subscopes, None)
- scope = ChangeScope(path, tree, spans, subscopes)
assert isinstance(tree, ScopeTree)
is_func = isinstance(tree, ptree.Function)
current_stmts = []
content = (
tree.children
if isinstance(tree, ptree.Module)
else cast(ptree.PythonNode, tree.get_suite()).children
)
for s in content:
# we don't create inner scopes for function contents
if is_func or _is_scope_statement(as_any(s)):
current_stmts.append(s)
else:
if current_stmts:
+ spans.append(StatementSpan(current_stmts, scope))
- spans.append(StatementSpan(current_stmts))
current_stmts = []
if current_stmts:
+ spans.append(StatementSpan(current_stmts, scope))
- spans.append(StatementSpan(current_stmts))
if is_func:
# we don't create inner scopes for function contents
return scope
for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
stree: ptree.Function | ptree.Class
+ name = cast(ptree.Name, stree.name).value
- spath = path.append(cast(ptree.Name, stree.name).value)
+ spath = path.append(name)
subscope = ChangeScope.from_tree(spath, stree)
+ subscope.parent_scope = scope
- subscopes[spath] = subscope
<0> return scope
| ===========unchanged ref 0===========
at: coeditor._utils
not_none(x: Optional[T1]) -> T1
assert_eq(x: T1, y: T1, message: Callable[[], str]=lambda: "") -> None
at: coeditor.code_change
_LineRange = NewType("LineRange", tuple[int, int])
_line_range(start: int, end: int, can_be_empty: bool=False) -> _LineRange
_strip_empty_lines(s: str)
at: coeditor.code_change.ChangeScope
path: ProjectPath
tree: ScopeTree
spans: Sequence["StatementSpan"]
subscopes: Mapping[str, Self]
parent_scope: "ChangeScope | None"
at: coeditor.code_change.ChangeScope.__post_init__
tree = self.tree
at: coeditor.code_change.StatementSpan.__post_init__
self.line_range: _LineRange = _line_range(start, end)
at: coeditor.common
count_lines(text: str) -> int
at: parso.tree
NodeOrLeaf()
at: parso.tree.BaseNode.__init__
self.children = children
self.parent: Optional[BaseNode] = None
at: parso.tree.NodeOrLeaf
__slots__ = ('parent',)
type: str
parent: 'Optional[BaseNode]'
get_code(include_prefix=True)
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
===========changed ref 0===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ def _search_span(self, line: int) -> "StatementSpan | None":
+ for span in self.spans:
+ if span.line_range[0] <= line < span.line_range[1]:
+ return span
+ return None
+
===========changed ref 1===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ def _search(self, path: ElemPath, line: int) -> Self | "StatementSpan":
+ scope = self._search_scope(path)
+ if scope.header_line_range[0] <= line < scope.header_line_range[1]:
+ return scope
+ span = scope._search_span(line)
+ return span or scope
+
===========changed ref 2===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ def _search_scope(self, path: ElemPath) -> Self:
+ """Find the scope that can potentially contain the given path. Follow the
+ path segments until no more subscopes are found."""
+ segs = path.split(".")
+ scope = self
+ for s in segs:
+ if s in scope.subscopes:
+ scope = scope.subscopes[s]
+ else:
+ break
+ return scope
+
===========changed ref 3===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
"""
A change scope is a python module, non-hidden function, or a non-hidden class, or a python module.
- functions and classes that are inside a parent function are considered hidden.
"""
path: ProjectPath
tree: ScopeTree
spans: Sequence["StatementSpan"]
+ subscopes: Mapping[str, Self]
- subscopes: Mapping[ProjectPath, Self]
+ parent_scope: "ChangeScope | None"
===========changed ref 4===========
# module: coeditor.history
@dataclass
class Modified(_ChangeBase[E1]):
+ @staticmethod
+ def from_unchanged(v: T1) -> "Modified[T1]":
+ return Modified(v, v, unchanged=True)
+
===========changed ref 5===========
# module: coeditor.history
@dataclass
class Modified(_ChangeBase[E1]):
before: E1
after: E1
+ unchanged: bool = False
===========changed ref 6===========
# module: coeditor.encoding
def change_to_line_diffs(change: Change[str]) -> list[str]:
"Encode a change as a token sequence."
match change:
case Modified(before, after):
+ if change.unchanged:
+ diffs = []
+ else:
+ diffs = compute_line_diffs(splitlines(before), splitlines(after))
- diffs = compute_line_diffs(splitlines(before), splitlines(after))
# rearrange_diffs_(diffs)
if not diffs:
# as a special case, `unified_diff` would return an empty when there is no change.
diffs = [" " + l for l in splitlines(before)]
case Added(after):
diffs = ["+" + l for l in splitlines(after)]
case Deleted(before):
diffs = ["-" + l for l in splitlines(before)]
case _:
raise ValueError(f"Invalid change type: {change}.")
return diffs
===========changed ref 7===========
# module: tests.coeditor.test_code_change
def test_change_scope():
code1 = dedent(
"""\
import os
x = 1
y = x + 1
def f1():
global x
x *= 5
return x
if __name__ == "__main__":
print(f1() + x)
@annotated
def f2():
return 1
@dataclass
class A:
attr1: int
@staticmethod
def method1():
return 1
class B:
inner_attr1: int
"""
)
mod_tree = code_to_module(code1)
scope = ChangeScope.from_tree(ProjectPath("code1", ""), mod_tree)
global_spans = [
dedent(
"""\
x = 1
y = x + 1
"""
),
dedent(
"""\
if __name__ == "__main__":
print(f1() + x)
"""
),
]
for i, code in enumerate(global_spans):
assert_str_equal(scope.spans[i].code, code)
f1_expect = dedent(
"""\
global x
x *= 5
return x
"""
)
+ f1_code = scope.subscopes["f1"].spans_code
- f1_code = scope.subscopes[ProjectPath("code1", "f1")].spans_code
assert_str_equal(f1_code, indent(f1_expect, " " * 4))
f2_expect = dedent(
"""\
@annotated
def f2():
return 1
"""
)
+ f2_code = scope.subscopes["f2"].all_code
- f2_code = scope.subscopes[ProjectPath("code1", "f2")].all_code
assert_str_equal(f2_code, f2</s> |
coeditor.code_change/JModuleChange.from_modules | Modified | temp-1 | d0fe36e93da8ca33161e524783335898bd47ebbc | - More analysis bug fix. - Encode unchanged using CSpan. | <0>:<add> module_change.map(lambda m: m.as_scope), tuple()
| # module: coeditor.code_change
@dataclass
class JModuleChange:
@staticmethod
def from_modules(module_change: Change[JModule]):
"Compute the change spans from two versions of the same module."
with _tlogger.timed("JModuleChange.from_modules"):
changed = dict[ProjectPath, ChangedSpan]()
for cspan in get_changed_spans(
- module_change.map(lambda m: m._to_scope()), tuple()
<0> ):
path = cspan.parent_scopes[-1].earlier().path
changed[path] = cspan
return JModuleChange(module_change, changed)
| ===========unchanged ref 0===========
at: coeditor.code_change.ChangedSpan
change: Change[str]
parent_scopes: Sequence[Change[ChangeScope]]
line_range: _LineRange
at: dataclasses
dataclass(_cls: Type[_T]) -> Type[_T]
dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]]
dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]
at: functools
cached_property(func: Callable[[Any], _T])
at: parso.python.tree
Module(children)
at: spot.static_analysis
ModuleName = str
===========changed ref 0===========
# module: coeditor.code_change
@dataclass
class JModule:
- def _to_scope(self) -> ChangeScope:
- return ChangeScope.from_tree(ProjectPath(self.mname, ""), self.tree)
-
===========changed ref 1===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ def ancestors(self) -> list[Self]:
+ scope = self
+ result = [scope]
+ while scope := scope.parent_scope:
+ result.append(scope)
+ result.reverse()
+ return result
+
===========changed ref 2===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ def _search_span(self, line: int) -> "StatementSpan | None":
+ for span in self.spans:
+ if span.line_range[0] <= line < span.line_range[1]:
+ return span
+ return None
+
===========changed ref 3===========
# module: coeditor.code_change
@dataclass
class StatementSpan:
"""
A statement span is a set of lines inside the same change scope. It is the basic unit of code changes handled by our model.
- For a modified function, the span is the function itself.
- For a modified module, the spans are the regions between the functions and classes plus
the spans recursively generated.
- For a modified class, the spans are the regions between methods plus
the spans recursively generated.
"""
statements: Sequence[PyNode]
+ scope: ChangeScope
===========changed ref 4===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ def _search(self, path: ElemPath, line: int) -> Self | "StatementSpan":
+ scope = self._search_scope(path)
+ if scope.header_line_range[0] <= line < scope.header_line_range[1]:
+ return scope
+ span = scope._search_span(line)
+ return span or scope
+
===========changed ref 5===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
+ def _search_scope(self, path: ElemPath) -> Self:
+ """Find the scope that can potentially contain the given path. Follow the
+ path segments until no more subscopes are found."""
+ segs = path.split(".")
+ scope = self
+ for s in segs:
+ if s in scope.subscopes:
+ scope = scope.subscopes[s]
+ else:
+ break
+ return scope
+
===========changed ref 6===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
"""
A change scope is a python module, non-hidden function, or a non-hidden class, or a python module.
- functions and classes that are inside a parent function are considered hidden.
"""
path: ProjectPath
tree: ScopeTree
spans: Sequence["StatementSpan"]
+ subscopes: Mapping[str, Self]
- subscopes: Mapping[ProjectPath, Self]
+ parent_scope: "ChangeScope | None"
===========changed ref 7===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
spans = []
subscopes = dict()
+ scope = ChangeScope(path, tree, spans, subscopes, None)
- scope = ChangeScope(path, tree, spans, subscopes)
assert isinstance(tree, ScopeTree)
is_func = isinstance(tree, ptree.Function)
current_stmts = []
content = (
tree.children
if isinstance(tree, ptree.Module)
else cast(ptree.PythonNode, tree.get_suite()).children
)
for s in content:
# we don't create inner scopes for function contents
if is_func or _is_scope_statement(as_any(s)):
current_stmts.append(s)
else:
if current_stmts:
+ spans.append(StatementSpan(current_stmts, scope))
- spans.append(StatementSpan(current_stmts))
current_stmts = []
if current_stmts:
+ spans.append(StatementSpan(current_stmts, scope))
- spans.append(StatementSpan(current_stmts))
if is_func:
# we don't create inner scopes for function contents
return scope
for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
stree: ptree.Function | ptree.Class
+ name = cast(ptree.Name, stree.name).value
- spath = path.append(cast(ptree.Name, stree.name).value)
+ spath = path.append(name)
subscope = ChangeScope.from_tree(spath, stree)
+ subscope.parent_scope = scope
+ subscopes[name] = subscope
- subscopes[spath] = subscope
return scope
===========changed ref 8===========
# module: coeditor.history
@dataclass
class Modified(_ChangeBase[E1]):
+ @staticmethod
+ def from_unchanged(v: T1) -> "Modified[T1]":
+ return Modified(v, v, unchanged=True)
+
===========changed ref 9===========
# module: coeditor.history
@dataclass
class Modified(_ChangeBase[E1]):
before: E1
after: E1
+ unchanged: bool = False
===========changed ref 10===========
# module: coeditor.encoding
def change_to_line_diffs(change: Change[str]) -> list[str]:
"Encode a change as a token sequence."
match change:
case Modified(before, after):
+ if change.unchanged:
+ diffs = []
+ else:
+ diffs = compute_line_diffs(splitlines(before), splitlines(after))
- diffs = compute_line_diffs(splitlines(before), splitlines(after))
# rearrange_diffs_(diffs)
if not diffs:
# as a special case, `unified_diff` would return an empty when there is no change.
diffs = [" " + l for l in splitlines(before)]
case Added(after):
diffs = ["+" + l for l in splitlines(after)]
case Deleted(before):
diffs = ["-" + l for l in splitlines(before)]
case _:
raise ValueError(f"Invalid change type: {change}.")
return diffs
|
coeditor.ctx_change_encoder/CtxCodeChangeProblemGenerator.encode_change | Modified | temp-1 | d0fe36e93da8ca33161e524783335898bd47ebbc | - More analysis bug fix. - Encode unchanged using CSpan. | <0>:<add> result.append(cspan)
| # module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def encode_change(
self,
pchange: JProjectChange,
mod2usages: Mapping[ModuleName, LineUsageAnalysis],
module_order: Sequence[ModuleName],
) -> Iterable[CtxCodeChangeProblem]:
<s>("."))
if path is None:
continue
+ jmod = before_mod_map[path.module]
+ scope = jmod.as_scope
+ elem = scope._search_scope(path.path)
+ match elem:
+ case ChangeScope(path=path, tree=ptree.Function()):
+ ancestors = elem.ancestors()
+ body_code = " " * len(ancestors) + "..."
+ h_end = elem.header_line_range[1]
+ cspan = ChangedSpan(
+ Modified.from_unchanged(body_code),
+ [Modified.from_unchanged(s) for s in ancestors],
+ _line_range(h_end, h_end + 1),
+ )
+ result.append(cspan)
+ case _:
+ cspan = ChangedSpan(
+ Modified.from_unchanged(f"path={path}"),
+ [Modified.from_unchanged(s) for s in elem.ancestors()],
+ _line_range(0, 1),
+ )
- result.append((ProjectPath(used.full_name, ""), str(used)))
<0> return result
sorted_cspans = list[ChangedSpan]()
for m in module_order:
if (mchange := pchange.changed.get(m)) is None:
continue
for span in mchange.changed.values():
if span.change.as_char() == Modified.as_char():
yield CtxCodeChangeProblem(
span,
relevant_changes=sorted_cspans.copy(),
relevant_unchanged=_get_relevant(span),
)
sorted_cspans.append(span)
| ===========above chunk 0===========
# module: coeditor.ctx_change_encoder
class CtxCodeChangeProblemGenerator(ProjectChangeProcessor[CtxCodeChangeProblem]):
def encode_change(
self,
pchange: JProjectChange,
mod2usages: Mapping[ModuleName, LineUsageAnalysis],
module_order: Sequence[ModuleName],
) -> Iterable[CtxCodeChangeProblem]:
# offset: -1
before_mod_map = {m.mname: m for m in pchange.all_modules.before}
mod_hier = ModuleHierarchy.from_modules(before_mod_map)
def _get_relevant(span: ChangedSpan):
if isinstance(span.change, Added):
# nothing to analyze
return []
path = span.parent_scopes[-1].earlier().path
line_usages = mod2usages[path.module]
all_used = set[PyDefinition]()
all_lines = set(range(*span.line_range))
all_lines.update(range(*span.header_line_range))
for l in all_lines:
for pydef in line_usages.line2usages.get(l, set()):
if (
+ pydef.full_name.startswith(path.module)
- pydef.full_name.startswith(pydef.import_module)
and pydef.start_pos[0] in all_lines
):
# skip self references
continue
all_used.add(pydef)
+ result = list[ChangedSpan]()
- result = list[tuple[ProjectPath, str]]()
for used in all_used:
path = mod_hier.resolve_path(used.full_name.split("."))
if path is None:
continue
+ jmod = before_mod_map[path.module]
</s>
===========unchanged ref 0===========
at: coeditor.code_change
_line_range(start: int, end: int, can_be_empty: bool=False) -> _LineRange
ChangeScope(path: ProjectPath, tree: ScopeTree, spans: Sequence["StatementSpan"], subscopes: Mapping[ProjectPath, Self])
ChangedSpan(change: Change[str], parent_scopes: Sequence[Change[ChangeScope]], line_range: _LineRange)
at: coeditor.code_change.ChangeScope
path: ProjectPath
tree: ScopeTree
spans: Sequence["StatementSpan"]
subscopes: Mapping[ProjectPath, Self]
at: coeditor.code_change.ChangedSpan
change: Change[str]
parent_scopes: Sequence[Change[ChangeScope]]
line_range: _LineRange
at: coeditor.ctx_change_encoder
CtxCodeChangeProblem(span: ChangedSpan, relevant_changes: list[ChangedSpan], relevant_unchanged: list[ChangedSpan])
PyDefinition(full_name: PyFullName, import_module: ModuleName, start_pos: tuple[int, int], end_pos: tuple[int, int])
LineUsageAnalysis(line2usages: Mapping[int, set[PyDefinition]])
at: coeditor.ctx_change_encoder.CtxCodeChangeProblemGenerator.post_edit_analysis
module_order = sort_modules_by_imports(module_deps)
at: coeditor.ctx_change_encoder.LineUsageAnalysis
line2usages: Mapping[int, set[PyDefinition]]
at: coeditor.ctx_change_encoder.PyDefinition
full_name: PyFullName
import_module: ModuleName
start_pos: tuple[int, int]
end_pos: tuple[int, int]
at: parso.python.tree
Function(children)
at: spot.static_analysis
ModuleName = str
ModuleHierarchy()
at: spot.static_analysis.ModuleHierarchy
resolve_path(segs: list[str]) -> ProjectPath | None
===========unchanged ref 1===========
from_modules(modules: Iterable[str]) -> "ModuleHierarchy"
at: spot.static_analysis.ProjectPath
module: ModuleName
path: ElemPath
at: typing
Iterable = _alias(collections.abc.Iterable, 1)
Mapping = _alias(collections.abc.Mapping, 2)
Sequence = _alias(collections.abc.Sequence, 1)
at: typing.Mapping
get(key: _KT) -> Optional[_VT_co]
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
# jedi.cache.clear_time_caches = lambda: None
@dataclass
class CtxCodeChangeProblem:
span: ChangedSpan
# most relevant to least relevant
relevant_changes: list[ChangedSpan]
# most relevant to least relevant
+ relevant_unchanged: list[ChangedSpan]
- relevant_unchanged: list[tuple[ProjectPath, str]]
===========changed ref 1===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
"""
A change scope is a python module, non-hidden function, or a non-hidden class, or a python module.
- functions and classes that are inside a parent function are considered hidden.
"""
path: ProjectPath
tree: ScopeTree
spans: Sequence["StatementSpan"]
+ subscopes: Mapping[str, Self]
- subscopes: Mapping[ProjectPath, Self]
+ parent_scope: "ChangeScope | None"
===========changed ref 2===========
# module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
+ @staticmethod
+ def from_name(name: classes.BaseName) -> Iterable["PyDefinition"]:
+ cast(classes.Name, name).is_definition()
+ if (
+ not name.in_builtin_module()
+ and (full_name := name.full_name)
+ and (import_module := name.module_name)
+ and (start_pos := name.get_definition_start_position())
+ and (end_pos := name.get_definition_end_position())
+ ):
+ full_name = PyFullName(full_name)
+ yield PyDefinition(full_name, import_module, start_pos, end_pos)
+
===========changed ref 3===========
# module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
- @staticmethod
- def from_signatures(name: classes.BaseName) -> Iterable["PyDefinition"]:
- cast(classes.Name, name).is_definition()
- if (
- not name.in_builtin_module()
- and (full_name := name.full_name)
- and (import_module := name.module_name)
- and (start_pos := name.get_definition_start_position())
- and (end_pos := name.get_definition_end_position())
- ):
- full_name = PyFullName(full_name)
- yield PyDefinition(full_name, import_module, start_pos, end_pos)
-
===========changed ref 4===========
# module: coeditor.history
@dataclass
class Modified(_ChangeBase[E1]):
+ @staticmethod
+ def from_unchanged(v: T1) -> "Modified[T1]":
+ return Modified(v, v, unchanged=True)
+
===========changed ref 5===========
# module: coeditor.history
@dataclass
class Modified(_ChangeBase[E1]):
before: E1
after: E1
+ unchanged: bool = False
===========changed ref 6===========
# module: coeditor.code_change
@dataclass
class JModule:
+ @cached_property
+ def as_scope(self) -> ChangeScope:
+ return ChangeScope.from_tree(ProjectPath(self.mname, ""), self.tree)
+
===========changed ref 7===========
# module: coeditor.code_change
@dataclass
class JModule:
- def _to_scope(self) -> ChangeScope:
- return ChangeScope.from_tree(ProjectPath(self.mname, ""), self.tree)
- |
coeditor.ctx_change_encoder/JediUsageAnalyzer.get_line_usages | Modified | temp-1 | d0fe36e93da8ca33161e524783335898bd47ebbc | - More analysis bug fix. - Encode unchanged using CSpan. | <0>:<add> usages.update(PyDefinition.from_name(d))
| # module: coeditor.ctx_change_encoder
@dataclass
class JediUsageAnalyzer:
def get_line_usages(
self,
script: jedi.Script,
proj_root: Path,
lines_to_analyze: Collection[int],
silent: bool = False,
):
jmod: tree.Module = script._module_node
line2usages = dict[int, set[PyDefinition]]()
all_names = [
name for k, names in jmod.get_used_names()._dict.items() for name in names
]
all_names.sort(key=lambda x: x.start_pos)
errors = self.error_counts
resolve_cache = dict[_ObjId, set[PyDefinition]]()
for name in tqdm(all_names, f"Analyzing {script.path}", disable=silent):
name: tree.Name
line = name.start_pos[0]
if line not in lines_to_analyze:
continue
usages = line2usages.setdefault(line, set())
try:
defs = fast_goto(
script,
name,
follow_imports=self.follow_imports,
follow_builtin_imports=False,
)
for d in defs:
- usages.update(PyDefinition.from_signatures(d))
<0>
except (AttributeError, AssertionError) as e:
text = repr(e)
errors[text] = errors.setdefault(text, 0) + 1
except ValueError as e:
# if the message is "not enough values to unpack"
if "not enough values to unpack (expected 2" in str(e):
errors[repr(e)] = errors.setdefault(str(e), 0) + 1
else:
raise
return LineUsageAnalysis(line2usages)
| ===========unchanged ref 0===========
at: coeditor._utils
TimeLogger(times: dict[str, list[float]]=field(default_factory=dict))
at: coeditor.ctx_change_encoder
PyDefinition(full_name: PyFullName, import_module: ModuleName, start_pos: tuple[int, int], end_pos: tuple[int, int])
_ObjId = NewType("_ObjId", int)
fast_goto(script: jedi.Script, tree_name: tree.Name, *, follow_imports=False, follow_builtin_imports=False, only_stubs=False, prefer_stubs=False) -> set[classes.Name]
at: coeditor.ctx_change_encoder.TkCtxCodeChangeEncoder
max_chunks_per_ref: int = 4
at: coeditor.ctx_change_encoder.TkCtxCodeChangeEncoder._group_encode_changed_refs
all_chunks = list[TokenSeq]()
mod_chunks = break_into_chunks(
file_tks,
lambda i: self._encode_parent_scopes(mod_change, i),
self.max_ref_tks,
overlap=self.ref_chunk_overlap,
max_return_chunks=self.max_chunks_per_ref,
)
at: dataclasses
dataclass(_cls: Type[_T]) -> Type[_T]
dataclass(*, init: bool=..., repr: bool=..., eq: bool=..., order: bool=..., unsafe_hash: bool=..., frozen: bool=...) -> Callable[[Type[_T]], Type[_T]]
dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]
at: jedi.api
Script(code=None, *, path=None, environment=None, project=None)
at: jedi.api.Script.__init__
self.path = path.absolute() if path else None
===========unchanged ref 1===========
self._module_node, code = self._inference_state.parse_and_get_code(
code=code,
path=self.path,
use_latest_grammar=path and path.suffix == '.pyi',
cache=False, # No disk cache, because the current script often changes.
diff_cache=settings.fast_parser,
cache_path=settings.cache_directory,
)
at: parso.python.tree
Name()
Module(children)
at: parso.python.tree.Module
__slots__ = ('_used_names',)
type = 'file_input'
get_used_names()
at: parso.python.tree.UsedNamesMapping.__init__
self._dict = dct
at: parso.tree.Leaf.__init__
self.start_pos = start_pos
at: pathlib
Path()
at: tqdm.std
tqdm(iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, write_bytes=False, lock_args=None, nrows=None, colour=None, delay=0, gui=False, **kwargs)
at: typing
Collection = _alias(collections.abc.Collection, 1)
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
@dataclass
class TkCtxCodeChangeEncoder:
+ def _group_encode_unchanged_refs(
+ self, elems: Sequence[ChangedSpan]
+ ) -> Sequence[TokenSeq]:
+ return self._group_encode_changed_refs(elems)
+
===========changed ref 1===========
# module: coeditor.ctx_change_encoder
@dataclass
class TkCtxCodeChangeEncoder:
- def _encode_unchanged_ref(
- self, path: ProjectPath, content: str
- ) -> Iterable[TokenSeq]:
- if (key := (path, content)) in self._value_cache:
- return self._value_cache[key]
- main_tks = encode_basic(f"#{str(path)}\n{content}")
- ref_chunks = (truncate_section(main_tks, TruncateAt.Right, self.max_ref_tks),)
- self._value_cache[key] = ref_chunks
- return ref_chunks
-
===========changed ref 2===========
# module: coeditor.ctx_change_encoder
@dataclass
class TkCtxCodeChangeEncoder:
def _encode_parent_scopes(
self, scope_changes: Sequence[Change[ChangeScope]], offset: int
) -> TokenSeq:
scope_tks = join_list((self._encode_scope_change(c) for c in scope_changes))
if offset != 0:
+ scope_tks.extend(encode_basic(f"# offset: {offset}\n"))
- ending = encode_basic(f"\n# offset: {offset}\n")
- else:
- ending = [Newline_id]
- scope_tks = truncate_section(
+ scope_tks = truncate_section(scope_tks, TruncateAt.Left, self.max_scope_tks)
- scope_tks + ending, TruncateAt.Left, self.max_scope_tks
- )
return scope_tks
===========changed ref 3===========
# module: coeditor.ctx_change_encoder
# jedi.cache.clear_time_caches = lambda: None
@dataclass
class CtxCodeChangeProblem:
span: ChangedSpan
# most relevant to least relevant
relevant_changes: list[ChangedSpan]
# most relevant to least relevant
+ relevant_unchanged: list[ChangedSpan]
- relevant_unchanged: list[tuple[ProjectPath, str]]
===========changed ref 4===========
# module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
+ @staticmethod
+ def from_name(name: classes.BaseName) -> Iterable["PyDefinition"]:
+ cast(classes.Name, name).is_definition()
+ if (
+ not name.in_builtin_module()
+ and (full_name := name.full_name)
+ and (import_module := name.module_name)
+ and (start_pos := name.get_definition_start_position())
+ and (end_pos := name.get_definition_end_position())
+ ):
+ full_name = PyFullName(full_name)
+ yield PyDefinition(full_name, import_module, start_pos, end_pos)
+
===========changed ref 5===========
# module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
- @staticmethod
- def from_signatures(name: classes.BaseName) -> Iterable["PyDefinition"]:
- cast(classes.Name, name).is_definition()
- if (
- not name.in_builtin_module()
- and (full_name := name.full_name)
- and (import_module := name.module_name)
- and (start_pos := name.get_definition_start_position())
- and (end_pos := name.get_definition_end_position())
- ):
- full_name = PyFullName(full_name)
- yield PyDefinition(full_name, import_module, start_pos, end_pos)
-
===========changed ref 6===========
# module: coeditor.history
@dataclass
class Modified(_ChangeBase[E1]):
+ @staticmethod
+ def from_unchanged(v: T1) -> "Modified[T1]":
+ return Modified(v, v, unchanged=True)
+
===========changed ref 7===========
# module: coeditor.history
@dataclass
class Modified(_ChangeBase[E1]):
before: E1
after: E1
+ unchanged: bool = False
|
coeditor.code_change/ChangeScope.__post_init__ | Modified | temp-1 | d58fffa6f57746cb134bd98b5de3a8e668c4311d | Finish unchanged ref encoding. | <0>:<add> self.header_line_range: LineRange = header_line_range
| # module: coeditor.code_change
@dataclass
class ChangeScope:
def __post_init__(self):
<s> = f"# module: {self.path.module}"
+ header_line_range = line_range(0, 0, can_be_empty=True)
- header_line_range = _line_range(0, 0, can_be_empty=True)
else:
h_start, h_end = 0, 0
tree = self.tree
to_visit = list[NodeOrLeaf]()
parent = not_none(tree.parent)
while parent.type in ("decorated", "async_funcdef"):
to_visit.insert(0, parent.children[0])
parent = not_none(parent.parent)
to_visit.extend(tree.children)
visited = list[NodeOrLeaf]()
for c in to_visit:
if c.type == "suite":
break
visited.append(c)
header_code = "".join(cast(str, c.get_code()) for c in visited)
header_code, _, e_right = _strip_empty_lines(header_code)
h_start = visited[0].start_pos[0]
h_end = visited[-1].end_pos[0] + 1 - e_right
assert_eq(count_lines(header_code) == h_end - h_start)
+ header_line_range = line_range(h_start, h_end)
- header_line_range = _line_range(h_start, h_end)
if self.spans and h_end > self.spans[0].line_range[0]:
raise ValueError(
f"Header covers the fisrt span: {self.path=}, {h_start=}, {h_end=} "
f"{self.spans[0].line_range=}"
)
self.header_code: str = header_code + "\n"
- self.header_line_range: _LineRange = header_line_range
<0>
| ===========above chunk 0===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
def __post_init__(self):
# offset: -1
# compute header
if isinstance(self.tree, ptree.Module):
header_code = f"# module: {self.path.module}"
+ header_line_range = line_range(0, 0,</s>
===========unchanged ref 0===========
at: coeditor._utils
not_none(x: Optional[T1]) -> T1
assert_eq(x: T1, y: T1, message: Callable[[], str]=lambda: "") -> None
at: coeditor.code_change
LineRange = NewType("LineRange", tuple[int, int])
line_range(start: int, end: int, can_be_empty: bool=False) -> LineRange
_strip_empty_lines(s: str)
at: coeditor.code_change.ChangeScope
path: ProjectPath
tree: ScopeTree
spans: Sequence["StatementSpan"]
subscopes: Mapping[str, Self]
parent_scope: "ChangeScope | None"
at: coeditor.code_change.StatementSpan.__post_init__
self.line_range: LineRange = line_range(start, end)
at: coeditor.common
count_lines(text: str) -> int
at: parso.python.tree
Module(children)
at: parso.tree
NodeOrLeaf()
at: parso.tree.BaseNode.__init__
self.children = children
self.parent: Optional[BaseNode] = None
at: parso.tree.NodeOrLeaf
__slots__ = ('parent',)
type: str
parent: 'Optional[BaseNode]'
get_code(include_prefix=True)
at: spot.static_analysis.ProjectPath
module: ModuleName
path: ElemPath
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
===========changed ref 0===========
# module: coeditor.code_change
- def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
- if not can_be_empty and start >= end:
- raise ValueError(f"Bad line range: {start=}, {end=}")
- return _LineRange((start, end))
-
===========changed ref 1===========
# module: coeditor.code_change
- def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
- if not can_be_empty and start >= end:
- raise ValueError(f"Bad line range: {start=}, {end=}")
- return _LineRange((start, end))
-
===========changed ref 2===========
# module: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
PyNode = ptree.PythonBaseNode | ptree.PythonNode
+ LineRange = NewType("LineRange", tuple[int, int])
- _LineRange = NewType("LineRange", tuple[int, int])
_tlogger = TimeLogger()
===========changed ref 3===========
# module: tests.coeditor.test_edits
class TestChangeIdentities:
cases = {
"empty": Modified("", ""),
"generation": Modified("", "123"),
"no change": Modified(
dedent(
"""\
def f1():
x = 1
"""
),
dedent(
"""\
def f1():
x = 1
"""
),
),
+ "unchanged=True": Modified.from_unchanged(
+ dedent(
+ """\
+ def f1():
+ x = 1
+ """
+ ),
+ ),
+ # this test case cannot pass for some reason. Tokenizer bug?
+ # "leading_whitespace": Modified.from_unchanged(" ..."),
"replace last": Modified(
dedent(
"""\
def f1():
x = 1"""
),
dedent(
"""\
def f1():
x = 2
return x * 2"""
),
),
"no special tokens": Modified(
dedent(
"""\
def f1():
x = 1
y = 2
z = x + y
return z
def f2():
f1()"""
),
dedent(
"""\
# new comment
def f_new():
x = 1
if x > 0:
y = 2 * x
y *= 2
z = x + y
return z
def f2():
f1()
return f_new() + a
new_var = 0
"""
),
),
"with special tokens": Modified(
dedent(
"""\
def f1():
x = "<add>"
y = "<del>\tx"
return x + y
"""
),
dedent(
"""\
# new comment 1
# new comment 2
def f1():
if newcond:
x = "<add</s>
===========changed ref 4===========
# module: tests.coeditor.test_edits
class TestChangeIdentities:
# offset: 1
<s>
# new comment 1
# new comment 2
def f1():
if newcond:
x = "<add>"
new_var = 5
y = "<del>"
return x + new_var + y
"""
),
),
"super long": Modified(
"\n".join(f"x = {i}" for i in range(0, 200)),
"\n".join(f"x = {2* (i // 2)}" for i in range(0, 200)),
),
}
|
coeditor.code_change/ChangeScope.from_tree | Modified | temp-1 | d58fffa6f57746cb134bd98b5de3a8e668c4311d | Finish unchanged ref encoding. | <0>:<add> spans.append(StatementSpan(len(spans), current_stmts, scope))
| # module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
spans = []
subscopes = dict()
scope = ChangeScope(path, tree, spans, subscopes, None)
assert isinstance(tree, ScopeTree)
is_func = isinstance(tree, ptree.Function)
current_stmts = []
content = (
tree.children
if isinstance(tree, ptree.Module)
else cast(ptree.PythonNode, tree.get_suite()).children
)
for s in content:
# we don't create inner scopes for function contents
if is_func or _is_scope_statement(as_any(s)):
current_stmts.append(s)
else:
if current_stmts:
+ spans.append(StatementSpan(len(spans), current_stmts, scope))
- spans.append(StatementSpan(current_stmts, scope))
current_stmts = []
if current_stmts:
- spans.append(StatementSpan(current_stmts, scope))
<0>
if is_func:
# we don't create inner scopes for function contents
return scope
for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
stree: ptree.Function | ptree.Class
name = cast(ptree.Name, stree.name).value
spath = path.append(name)
subscope = ChangeScope.from_tree(spath, stree)
subscope.parent_scope = scope
subscopes[name] = subscope
return scope
| ===========unchanged ref 0===========
at: coeditor._utils
as_any(x) -> Any
at: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
ChangeScope(path: ProjectPath, tree: ScopeTree, spans: Sequence["StatementSpan"], subscopes: Mapping[str, Self], parent_scope: "ChangeScope | None")
_is_scope_statement(stmt: PyNode) -> bool
StatementSpan(nth_in_parent: int, statements: Sequence[PyNode], scope: ChangeScope)
at: coeditor.code_change.ChangeScope
parent_scope: "ChangeScope | None"
at: parso.python.tree
PythonNode()
Name()
Module(children)
Class(children)
Function(children)
at: parso.python.tree.Class
type = 'classdef'
__slots__ = ()
at: parso.python.tree.ClassOrFunc
__slots__ = ()
at: parso.python.tree.Function
type = 'funcdef'
at: parso.python.tree.Scope
__slots__ = ()
_search_in_scope(*names)
get_suite()
at: parso.tree.BaseNode.__init__
self.children = children
at: parso.tree.Leaf.__init__
self.value = value
at: spot.static_analysis
ProjectPath(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any)
at: spot.static_analysis.ProjectPath
append(path: ElemPath) -> "ProjectPath"
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
===========changed ref 0===========
# module: coeditor.code_change
- def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
- if not can_be_empty and start >= end:
- raise ValueError(f"Bad line range: {start=}, {end=}")
- return _LineRange((start, end))
-
===========changed ref 1===========
# module: coeditor.code_change
- def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
- if not can_be_empty and start >= end:
- raise ValueError(f"Bad line range: {start=}, {end=}")
- return _LineRange((start, end))
-
===========changed ref 2===========
# module: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
PyNode = ptree.PythonBaseNode | ptree.PythonNode
+ LineRange = NewType("LineRange", tuple[int, int])
- _LineRange = NewType("LineRange", tuple[int, int])
_tlogger = TimeLogger()
===========changed ref 3===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
def __post_init__(self):
# compute header
if isinstance(self.tree, ptree.Module):
header_code = f"# module: {self.path.module}"
+ header_line_range = line_range(0, 0, can_be_empty=True)
- header_line_range = _line_range(0, 0, can_be_empty=True)
else:
h_start, h_end = 0, 0
tree = self.tree
to_visit = list[NodeOrLeaf]()
parent = not_none(tree.parent)
while parent.type in ("decorated", "async_funcdef"):
to_visit.insert(0, parent.children[0])
parent = not_none(parent.parent)
to_visit.extend(tree.children)
visited = list[NodeOrLeaf]()
for c in to_visit:
if c.type == "suite":
break
visited.append(c)
header_code = "".join(cast(str, c.get_code()) for c in visited)
header_code, _, e_right = _strip_empty_lines(header_code)
h_start = visited[0].start_pos[0]
h_end = visited[-1].end_pos[0] + 1 - e_right
assert_eq(count_lines(header_code) == h_end - h_start)
+ header_line_range = line_range(h_start, h_end)
- header_line_range = _line_range(h_start, h_end)
if self.spans and h_end > self.spans[0].line_range[0]:
raise ValueError(
f"Header covers the fisrt span: {self.path=}, {h_start=}, {h_end=} "
f"{self.spans[0].line_range=}"
)
self.header_code: str = header_code + "\n"</s>
===========changed ref 4===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
def __post_init__(self):
# offset: 1
<s>spans[0].line_range=}"
)
self.header_code: str = header_code + "\n"
+ self.header_line_range: LineRange = header_line_range
- self.header_line_range: _LineRange = header_line_range
===========changed ref 5===========
# module: tests.coeditor.test_edits
class TestChangeIdentities:
cases = {
"empty": Modified("", ""),
"generation": Modified("", "123"),
"no change": Modified(
dedent(
"""\
def f1():
x = 1
"""
),
dedent(
"""\
def f1():
x = 1
"""
),
),
+ "unchanged=True": Modified.from_unchanged(
+ dedent(
+ """\
+ def f1():
+ x = 1
+ """
+ ),
+ ),
+ # this test case cannot pass for some reason. Tokenizer bug?
+ # "leading_whitespace": Modified.from_unchanged(" ..."),
"replace last": Modified(
dedent(
"""\
def f1():
x = 1"""
),
dedent(
"""\
def f1():
x = 2
return x * 2"""
),
),
"no special tokens": Modified(
dedent(
"""\
def f1():
x = 1
y = 2
z = x + y
return z
def f2():
f1()"""
),
dedent(
"""\
# new comment
def f_new():
x = 1
if x > 0:
y = 2 * x
y *= 2
z = x + y
return z
def f2():
f1()
return f_new() + a
new_var = 0
"""
),
),
"with special tokens": Modified(
dedent(
"""\
def f1():
x = "<add>"
y = "<del>\tx"
return x + y
"""
),
dedent(
"""\
# new comment 1
# new comment 2
def f1():
if newcond:
x = "<add</s> |
coeditor.code_change/StatementSpan.__post_init__ | Modified | temp-1 | d58fffa6f57746cb134bd98b5de3a8e668c4311d | Finish unchanged ref encoding. | <0>:<add> self.line_range: LineRange = line_range(start, end)
| # module: coeditor.code_change
@dataclass
class StatementSpan:
def __post_init__(self):
assert self.statements
+ # remove leading newlines
+ n_leading_newlines = 0
+ stmts = self.statements
+ for s in stmts:
+ if s.type == ptree.Newline.type:
+ n_leading_newlines += 1
+ else:
+ break
+ if n_leading_newlines:
+ self.statements = stmts[n_leading_newlines:]
+
origin_code = "".join(s.get_code() for s in self.statements)
code, _, e_right = _strip_empty_lines(origin_code)
start = self.statements[0].start_pos[0]
end = self.statements[-1].end_pos[0] + 1 - e_right
self.code: str = code + "\n"
try:
- self.line_range: _LineRange = _line_range(start, end)
<0> except ValueError:
print_err(f"{origin_code=}, {e_right=}, {start=}, {end=}")
raise
| ===========unchanged ref 0===========
at: coeditor.code_change.StatementSpan
nth_in_parent: int
statements: Sequence[PyNode]
scope: ChangeScope
at: parso.python.tree
Newline()
at: parso.python.tree.Newline
__slots__ = ()
type = 'newline'
===========changed ref 0===========
# module: coeditor.code_change
@dataclass
class StatementSpan:
"""
A statement span is a set of lines inside the same change scope. It is the basic unit of code changes handled by our model.
- For a modified function, the span is the function itself.
- For a modified module, the spans are the regions between the functions and classes plus
the spans recursively generated.
- For a modified class, the spans are the regions between methods plus
the spans recursively generated.
"""
+ nth_in_parent: int
statements: Sequence[PyNode]
scope: ChangeScope
===========changed ref 1===========
# module: coeditor.code_change
- def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
- if not can_be_empty and start >= end:
- raise ValueError(f"Bad line range: {start=}, {end=}")
- return _LineRange((start, end))
-
===========changed ref 2===========
# module: coeditor.code_change
- def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
- if not can_be_empty and start >= end:
- raise ValueError(f"Bad line range: {start=}, {end=}")
- return _LineRange((start, end))
-
===========changed ref 3===========
# module: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
PyNode = ptree.PythonBaseNode | ptree.PythonNode
+ LineRange = NewType("LineRange", tuple[int, int])
- _LineRange = NewType("LineRange", tuple[int, int])
_tlogger = TimeLogger()
===========changed ref 4===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
spans = []
subscopes = dict()
scope = ChangeScope(path, tree, spans, subscopes, None)
assert isinstance(tree, ScopeTree)
is_func = isinstance(tree, ptree.Function)
current_stmts = []
content = (
tree.children
if isinstance(tree, ptree.Module)
else cast(ptree.PythonNode, tree.get_suite()).children
)
for s in content:
# we don't create inner scopes for function contents
if is_func or _is_scope_statement(as_any(s)):
current_stmts.append(s)
else:
if current_stmts:
+ spans.append(StatementSpan(len(spans), current_stmts, scope))
- spans.append(StatementSpan(current_stmts, scope))
current_stmts = []
if current_stmts:
+ spans.append(StatementSpan(len(spans), current_stmts, scope))
- spans.append(StatementSpan(current_stmts, scope))
if is_func:
# we don't create inner scopes for function contents
return scope
for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
stree: ptree.Function | ptree.Class
name = cast(ptree.Name, stree.name).value
spath = path.append(name)
subscope = ChangeScope.from_tree(spath, stree)
subscope.parent_scope = scope
subscopes[name] = subscope
return scope
===========changed ref 5===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
def __post_init__(self):
# compute header
if isinstance(self.tree, ptree.Module):
header_code = f"# module: {self.path.module}"
+ header_line_range = line_range(0, 0, can_be_empty=True)
- header_line_range = _line_range(0, 0, can_be_empty=True)
else:
h_start, h_end = 0, 0
tree = self.tree
to_visit = list[NodeOrLeaf]()
parent = not_none(tree.parent)
while parent.type in ("decorated", "async_funcdef"):
to_visit.insert(0, parent.children[0])
parent = not_none(parent.parent)
to_visit.extend(tree.children)
visited = list[NodeOrLeaf]()
for c in to_visit:
if c.type == "suite":
break
visited.append(c)
header_code = "".join(cast(str, c.get_code()) for c in visited)
header_code, _, e_right = _strip_empty_lines(header_code)
h_start = visited[0].start_pos[0]
h_end = visited[-1].end_pos[0] + 1 - e_right
assert_eq(count_lines(header_code) == h_end - h_start)
+ header_line_range = line_range(h_start, h_end)
- header_line_range = _line_range(h_start, h_end)
if self.spans and h_end > self.spans[0].line_range[0]:
raise ValueError(
f"Header covers the fisrt span: {self.path=}, {h_start=}, {h_end=} "
f"{self.spans[0].line_range=}"
)
self.header_code: str = header_code + "\n"</s>
===========changed ref 6===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
def __post_init__(self):
# offset: 1
<s>spans[0].line_range=}"
)
self.header_code: str = header_code + "\n"
+ self.header_line_range: LineRange = header_line_range
- self.header_line_range: _LineRange = header_line_range
|
coeditor.ctx_change_encoder/PyDefinition.from_name | Modified | temp-1 | d58fffa6f57746cb134bd98b5de3a8e668c4311d | Finish unchanged ref encoding. | <0>:<add> raise ValueError(f"Inconsistent module: {full_name=}, {import_module=}")
| # module: coeditor.ctx_change_encoder
@dataclass(unsafe_hash=True)
class PyDefinition:
@staticmethod
def from_name(name: classes.BaseName) -> Iterable["PyDefinition"]:
- cast(classes.Name, name).is_definition()
if (
not name.in_builtin_module()
and (full_name := name.full_name)
and (import_module := name.module_name)
and (start_pos := name.get_definition_start_position())
and (end_pos := name.get_definition_end_position())
):
full_name = PyFullName(full_name)
+ if not full_name.startswith(import_module):
<0> yield PyDefinition(full_name, import_module, start_pos, end_pos)
| ===========unchanged ref 0===========
at: coeditor.ctx_change_encoder
PyFullName = NewType("PyFullName", str)
at: coeditor.ctx_change_encoder.PyDefinition
full_name: PyFullName
import_module: ModuleName
start_pos: tuple[int, int]
end_pos: tuple[int, int]
at: jedi.api.classes
BaseName(inference_state, name)
at: jedi.api.classes.BaseName
_mapping = {
'posixpath': 'os.path',
'riscospath': 'os.path',
'ntpath': 'os.path',
'os2emxpath': 'os.path',
'macpath': 'os.path',
'genericpath': 'os.path',
'posix': 'os',
'_io': 'io',
'_functools': 'functools',
'_collections': 'collections',
'_socket': 'socket',
'_sqlite3': 'sqlite3',
}
_tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in {
'argparse._ActionsContainer': 'argparse.ArgumentParser',
}.items())
in_builtin_module()
get_definition_start_position()
get_definition_end_position()
at: typing
Iterable = _alias(collections.abc.Iterable, 1)
===========changed ref 0===========
# module: coeditor.ctx_change_encoder
+ PyFullName = NewType("PyFullName", str)
- PyFullName = NewType("PyPathStr", str)
===========changed ref 1===========
# module: coeditor.code_change
- def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
- if not can_be_empty and start >= end:
- raise ValueError(f"Bad line range: {start=}, {end=}")
- return _LineRange((start, end))
-
===========changed ref 2===========
# module: coeditor.code_change
- def _line_range(start: int, end: int, can_be_empty: bool = False) -> _LineRange:
- if not can_be_empty and start >= end:
- raise ValueError(f"Bad line range: {start=}, {end=}")
- return _LineRange((start, end))
-
===========changed ref 3===========
# module: coeditor.code_change
@dataclass
class ChangedSpan:
"Represents the changes made to a statement span."
change: Change[str]
parent_scopes: Sequence[Change[ChangeScope]]
+ line_range: LineRange
- line_range: _LineRange
===========changed ref 4===========
# module: coeditor.code_change
ScopeTree = ptree.Function | ptree.Class | ptree.Module
PyNode = ptree.PythonBaseNode | ptree.PythonNode
+ LineRange = NewType("LineRange", tuple[int, int])
- _LineRange = NewType("LineRange", tuple[int, int])
_tlogger = TimeLogger()
===========changed ref 5===========
# module: coeditor.code_change
@dataclass
class StatementSpan:
"""
A statement span is a set of lines inside the same change scope. It is the basic unit of code changes handled by our model.
- For a modified function, the span is the function itself.
- For a modified module, the spans are the regions between the functions and classes plus
the spans recursively generated.
- For a modified class, the spans are the regions between methods plus
the spans recursively generated.
"""
+ nth_in_parent: int
statements: Sequence[PyNode]
scope: ChangeScope
===========changed ref 6===========
# module: coeditor.code_change
@dataclass
class StatementSpan:
def __post_init__(self):
assert self.statements
+ # remove leading newlines
+ n_leading_newlines = 0
+ stmts = self.statements
+ for s in stmts:
+ if s.type == ptree.Newline.type:
+ n_leading_newlines += 1
+ else:
+ break
+ if n_leading_newlines:
+ self.statements = stmts[n_leading_newlines:]
+
origin_code = "".join(s.get_code() for s in self.statements)
code, _, e_right = _strip_empty_lines(origin_code)
start = self.statements[0].start_pos[0]
end = self.statements[-1].end_pos[0] + 1 - e_right
self.code: str = code + "\n"
try:
+ self.line_range: LineRange = line_range(start, end)
- self.line_range: _LineRange = _line_range(start, end)
except ValueError:
print_err(f"{origin_code=}, {e_right=}, {start=}, {end=}")
raise
===========changed ref 7===========
# module: coeditor.code_change
@dataclass
class ChangeScope:
@staticmethod
def from_tree(path: ProjectPath, tree: ScopeTree) -> "ChangeScope":
spans = []
subscopes = dict()
scope = ChangeScope(path, tree, spans, subscopes, None)
assert isinstance(tree, ScopeTree)
is_func = isinstance(tree, ptree.Function)
current_stmts = []
content = (
tree.children
if isinstance(tree, ptree.Module)
else cast(ptree.PythonNode, tree.get_suite()).children
)
for s in content:
# we don't create inner scopes for function contents
if is_func or _is_scope_statement(as_any(s)):
current_stmts.append(s)
else:
if current_stmts:
+ spans.append(StatementSpan(len(spans), current_stmts, scope))
- spans.append(StatementSpan(current_stmts, scope))
current_stmts = []
if current_stmts:
+ spans.append(StatementSpan(len(spans), current_stmts, scope))
- spans.append(StatementSpan(current_stmts, scope))
if is_func:
# we don't create inner scopes for function contents
return scope
for stree in tree._search_in_scope(ptree.Function.type, ptree.Class.type):
stree: ptree.Function | ptree.Class
name = cast(ptree.Name, stree.name).value
spath = path.append(name)
subscope = ChangeScope.from_tree(spath, stree)
subscope.parent_scope = scope
subscopes[name] = subscope
return scope
|
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 52