by Panzerschrek · 1mo ago · 0 comments
def first(items: list[Reading]) -> Reading:
return items[0] # a reference into the caller's list
How the compiler knows and checks if the returning reference is derived from one of arguments? What if a function returning a reference has more than one parameter? I my language I needed to implement a whole notation to allow describing relations between parameters and returned references, has TurboPython something similar? def choose(a: list[Reading], b: list[Reading], choose_a: bool) -> Reading:
if choose_a:
return a[0]
return b[0]
the return borrows from either a or b, the caller gets a warning when b is modified while the borrow is held.
OTOH returning a reference to an local object is an error; locals can be returned by ownership-passing (Own[Reading] -- NRVO in C++).
Currently the analysis happens on AST level, so it has it's drawback. I'm working on a CFG based MIR, to make this less coarse, though that's still a while since it's ready.Good. My language has such ability too (if return type is specified as auto). But I do need a notation for some cases, like if no body definition is available or for recursive functions. How do you deal with recursion?
> the caller gets a warning when b is modified while the borrow is held
Why a warning and not an error?
@cpp_template("::tpy::min_key({0}, {1}, {2})", borrows=("a", "b"))
def min[T, K: Comparable](a: T, b: T, key: Fn[[T], K]) -> T: ...
(the result may borrow either a or b)Current approach is to warn because the checks are less precise than what I'd like them to. The idea is to keep it that way for now, migrate to CFG in the future and enable it in a strict mode.