Skip to content

Commit 9a738f4

Browse files
lkdvosclaude
andcommitted
Identify internal LineNumberNodes by the input expression, not by path
Follow-up on the previous commit, addressing the two open questions in the PR discussion. Instead of recognizing parser-generated `LineNumberNode`s by string-prefix matching against `TensorOperations/src`, snapshot the set of files referenced by the `LineNumberNode`s of the expression handed to the parser -- taken before any preprocessor runs, so those are by construction exactly the user's line numbers -- and drop everything else. This also explains why the step cannot be a stateless entry in `parser.postprocessors`: it needs state captured before the preprocessors. The path-prefix version missed two cases: - `ext/`, which lies outside `src/`, so no extension was covered; - `@planar`/`@plansor`, where TensorKit's own pre/postprocessors synthesize `LineNumberNode`s pointing into `TensorKit/src/planar/`. Verified that those are now stripped as well, so `@planar` and `@plansor` are fixed with no TensorKit-side change. Note that both halves of this are needed, i.e. the removal is not merely cosmetic: a synthesized `LineNumberNode` in block-statement position re-attributes every statement that follows it to a line in TensorOperations' own source, which steals the attribution from the user's line. Conversely, `LineNumberNode`s outside block-statement position are left alone, since they can be structurally required -- the `costcheck = :warn` path emits a `@warn` macrocall whose second argument is one. Verified end to end with `--code-coverage`: on PEPSKit's `src/algorithms/contractions/ctmrg/enlarge_corner.jl` (the file from #280), the four contraction statements of `enlarge_northwest_corner` go from no coverage information at all to a hit count, taking the file from 12/72 to 28/88 reported lines. A deliberately-never-called function stays at 0 in both cases, confirming the counts reflect real execution. Also checked on the realistic CI path, i.e. `Pkg.test(coverage = true)` against a precompiled package rather than an `include`d file. While here: - delete `removelinenumbernode`, which is unexported and now unused; - drop the redundant removal in `insertcontractiontrees!`, since its output passes through the parser's final pass anyway; - update `docs/src/man/implementation.md`, which still listed `removelinenumbernode` as an enabled default postprocessor; - tighten the tests to assert the exact set of surviving line numbers and that every one of them comes from the test file, which the previous prefix-based assertion could not detect for `ext/`. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent d630dec commit 9a738f4

8 files changed

Lines changed: 144 additions & 82 deletions

File tree

‎Project.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "TensorOperations"
22
uuid = "6aa20fa7-93e2-5fca-9bc0-fbd0db3c71a2"
3-
version = "5.6.2"
3+
version = "5.6.3"
44
authors = ["Lukas Devos <lukas.devos@ugent.be>", "Maarten Van Damme <maartenvd1994@gmail.com>", "Jutho Haegeman <jutho.haegeman@ugent.be>"]
55

66
[deps]

‎docs/src/man/implementation.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,13 +77,17 @@ objects.
7777

7878
```@docs
7979
TensorOperations._flatten
80-
TensorOperations.removelinenumbernode
8180
TensorOperations.addtensoroperations
8281
TensorOperations.insertargument
8382
TensorOperations.insertbackend
8483
TensorOperations.insertallocator
8584
```
8685

86+
Finally, after all postprocessors have run, the parser strips the `LineNumberNode`s that it
87+
synthesized itself, while preserving the ones that came from the user's code. As a result the
88+
generated code stays attributable to the lines of the original `@tensor` expression, which is
89+
what makes those lines show up in code coverage reports and in stacktraces.
90+
8791
## Analysis of contraction graphs and optimizing contraction order
8892

8993
The macro [`@tensoropt`](@ref) or the combination of [`@tensor`](@ref) with the keyword

‎src/indexnotation/contractiontrees.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ function insertcontractiontrees!(
163163
end
164164
)
165165
end
166-
push!(postexprs, removeinternallinenumbernodes(costcompareex))
166+
push!(postexprs, costcompareex)
167167
return treeex
168168
end
169169

‎src/indexnotation/parser.jl‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ end
2323

2424
function (parser::TensorParser)(ex::Expr)
2525
verifytensorexpr(ex)
26+
# any `LineNumberNode` present here belongs to the user's code: record its file so that the
27+
# ones synthesized further down can be told apart and removed again at the very end
28+
userfiles = linenumberfiles(ex)
2629
for p in parser.preprocessors
2730
ex = p(ex)::Expr
2831
end
@@ -34,7 +37,8 @@ function (parser::TensorParser)(ex::Expr)
3437
for p in parser.postprocessors
3538
ex = p(ex)::Expr
3639
end
37-
ex = removeinternallinenumbernodes(ex)::Expr
40+
# this has to happen after all (possibly user-supplied) postprocessors have run
41+
ex = removeinternallinenumbernodes(ex, userfiles)::Expr
3842
return ex
3943
end
4044

‎src/indexnotation/postprocessors.jl‎

Lines changed: 38 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -30,57 +30,61 @@ function _flatten(ex)
3030
end
3131
end
3232

33-
# package source directory (with trailing separator), used to recognize `LineNumberNode`s that
34-
# point into the parser's own `quote` blocks rather than into user code.
35-
const _PARSER_SRCDIR = joinpath(dirname(@__DIR__), "")
36-
37-
_isinternallinenumber(@nospecialize(x)) =
38-
x isa LineNumberNode && startswith(String(x.file), _PARSER_SRCDIR)
39-
4033
"""
41-
removeinternallinenumbernodes(ex)
34+
linenumberfiles(ex, files = Set{Symbol}())
35+
36+
Collect the set of files referenced by the `LineNumberNode`s in `ex`.
4237
43-
Remove all `LineNumberNode`s that point into the TensorOperations source tree, i.e. the ones
44-
introduced by the parser's own `quote` blocks. `LineNumberNode`s originating from user code are
45-
kept, so that the generated code remains attributable to the user's source lines (e.g. for code
46-
coverage).
38+
This is used on the expression that is handed to a [`TensorParser`](@ref), before any
39+
processing takes place, to determine which `LineNumberNode`s belong to the user's code:
40+
see [`removeinternallinenumbernodes`](@ref).
4741
"""
48-
function removeinternallinenumbernodes(ex)
49-
if isexpr(ex, :block)
50-
# within a block, `LineNumberNode`s are statement markers: drop the internal ones
51-
args = Any[
52-
removeinternallinenumbernodes(e) for e in ex.args
53-
if !_isinternallinenumber(e)
54-
]
55-
return Expr(:block, args...)
56-
elseif isa(ex, Expr)
57-
# elsewhere (e.g. the mandatory 2nd argument of a `:macrocall`) a `LineNumberNode` may
58-
# be structurally required, so keep all positions and only recurse into nested blocks
59-
return Expr(ex.head, Any[removeinternallinenumbernodes(e) for e in ex.args]...)
60-
else
61-
return ex
42+
function linenumberfiles(ex, files = Set{Symbol}())
43+
if ex isa LineNumberNode
44+
push!(files, ex.file)
45+
elseif ex isa Expr
46+
foreach(e -> linenumberfiles(e, files), ex.args)
6247
end
48+
return files
6349
end
6450

6551
"""
66-
removelinenumbernode(ex)
52+
removeinternallinenumbernodes(ex, userfiles)
6753
68-
Remove all `LineNumberNode`s from an expression.
54+
Remove the `LineNumberNode`s that were synthesized by the parser, i.e. the ones whose file is
55+
not in `userfiles`, as obtained from [`linenumberfiles`](@ref) on the original expression.
6956
70-
!!! note
71-
Kept for backwards compatibility. The parser now uses
72-
[`removeinternallinenumbernodes`](@ref), which preserves user `LineNumberNode`s so that
73-
generated code stays attributable to the user's source lines (e.g. for code coverage).
57+
`LineNumberNode`s originating from user code are kept, so that the generated code remains
58+
attributable to the user's source lines. This matters for code coverage: Julia only emits a
59+
coverage counter for a line that a `LineNumberNode` points at, so stripping the user's
60+
`LineNumberNode`s leaves every statement of a `@tensor begin ... end` block after the first one
61+
without any coverage information at all. Conversely, a synthesized `LineNumberNode` would
62+
re-attribute all statements that follow it to a line in the parser's own source, so both halves
63+
are needed.
7464
"""
75-
function removelinenumbernode(ex)
65+
function removeinternallinenumbernodes(ex, userfiles)
7666
if isexpr(ex, :block)
77-
args = [removelinenumbernode(e) for e in ex.args if !(e isa LineNumberNode)]
67+
# within a block, `LineNumberNode`s are statement markers: drop the internal ones
68+
args = Any[
69+
removeinternallinenumbernodes(e, userfiles) for e in ex.args
70+
if !_isinternallinenumber(e, userfiles)
71+
]
7872
return Expr(:block, args...)
73+
elseif isa(ex, Expr)
74+
# elsewhere a `LineNumberNode` may be structurally required -- most notably as the
75+
# mandatory 2nd argument of a `:macrocall` -- so keep all positions here and only
76+
# recurse into nested blocks
77+
return Expr(
78+
ex.head, Any[removeinternallinenumbernodes(e, userfiles) for e in ex.args]...
79+
)
7980
else
8081
return ex
8182
end
8283
end
8384

85+
_isinternallinenumber(@nospecialize(x), userfiles) =
86+
x isa LineNumberNode && x.file ∉ userfiles
87+
8488
# list of functions that are used in expressions produced by `@tensor`
8589
const tensoroperationsfunctions = (
8690
:tensoralloc, :tensorfree!,

‎test/butensor.jl‎

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,17 @@ end
77

88
using Bumper
99
@testset "@butensor preserves user line numbers (issue #280)" begin
10-
# `@butensor` wraps the block in an inner `@tensor`; make sure it does not strip the user's
11-
# line numbers, and does not leak TensorOperations-internal ones.
12-
pkgsrc = dirname(pathof(TensorOperations))
13-
lnns = LineNumberNode[]
14-
collect_lnns(x) = x isa LineNumberNode ? push!(lnns, x) :
15-
x isa Expr && foreach(collect_lnns, x.args)
16-
collect_lnns(
17-
@macroexpand @butensor begin
18-
T[a, b] := X[a, c] * Y[c, b]
19-
Z[a, b] := T[a, c] * W[c, b]
20-
end
21-
)
22-
@test !any(l -> startswith(String(l.file), pkgsrc), lnns)
23-
@test count(l -> String(l.file) == @__FILE__, lnns) >= 2
10+
# `@butensor` wraps the block in an inner `@tensor`, so the expansion has to be recursive
11+
# here to reach the code that the parser generated. This also covers the extension itself:
12+
# `_butensor` must not introduce `LineNumberNode`s pointing into `ext/`.
13+
firstline = @__LINE__() + 2
14+
block = @macroexpand @butensor begin
15+
T[a, b] := X[a, c] * Y[c, b]
16+
Z[a, b] := T[a, c] * W[c, b]
17+
end
18+
lnns = statementlinenumbernodes(block)
19+
@test all(l -> l.file === Symbol(@__FILE__), lnns)
20+
@test sort!(unique(l.line for l in lnns)) == collect(firstline .+ (0:1))
2421
end
2522

2623
@testset "Bumper tests with eltype $T" for T in (Float32, ComplexF64)

‎test/macro_kwargs.jl‎

Lines changed: 65 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -94,51 +94,86 @@ end
9494

9595
# https://github.com/QuantumKitHub/TensorOperations.jl/issues/280: the generated code must keep
9696
# the user's `LineNumberNode`s (so `@tensor` lines show up in code coverage) while dropping the
97-
# parser's own internal ones (which would otherwise pollute the package's coverage).
97+
# parser's own, which would steal that attribution. See `statementlinenumbernodes` in
98+
# `runtests.jl` for why only block-statement positions are inspected. `@macroexpand1` is used
99+
# throughout so that we look at what `@tensor` itself produced, and not at the expansion of
100+
# macros that it merely passes through (e.g. the `@warn` of the `costcheck` path).
98101
@testset "line numbers (issue #280)" begin
99-
collectlinenumbernodes(ex, acc = LineNumberNode[]) =
100-
(
101-
ex isa LineNumberNode ? push!(acc, ex) :
102-
ex isa Expr && foreach(e -> collectlinenumbernodes(e, acc), ex.args); acc
103-
)
104-
pkgsrc = dirname(pathof(TensorOperations))
105-
pkglnns(lnns) = filter(l -> startswith(String(l.file), pkgsrc), lnns)
106-
userlines(lnns) = sort!(unique!([l.line for l in lnns if String(l.file) == @__FILE__]))
107-
108-
@testset "no internal LineNumberNodes leak into generated code" begin
109-
# covers the scalar, dst-reuse and checkpoint `quote` paths in the parser
102+
thisfile = Symbol(@__FILE__)
103+
104+
@testset "single-statement expressions carry no LineNumberNodes" begin
105+
# nothing to preserve here: the input has no `LineNumberNode`s of its own, and the
106+
# statement is attributed to the line of the `@tensor` call by the surrounding scope
110107
exprs = [
111-
@macroexpand(@tensor T[a, b] := A[a, c] * B[c, b]),
112-
@macroexpand(@tensor R[a, b] := A[a, c] * B[c, d] * C[d, e] * E[e, f] * F[f, b]),
113-
@macroexpand(@tensor s = X[a, b] * Y[a, b]),
114-
@macroexpand(@tensoropt R[a, b] := A[a, c] * B[c, d] * C[d, e] * E[e, b]),
115-
@macroexpand(@tensor allocator = alloc R[a, b] := A[a, c] * B[c, d] * C[d, b]),
116-
@macroexpand(@tensor costcheck = warn R[a, b] := A[a, c] * B[c, d] * C[d, b]),
117-
@macroexpand(@tensor contractcheck = true R[a, b] := A[a, c] * B[c, b]),
108+
@macroexpand1(@tensor T[a, b] := A[a, c] * B[c, b]),
109+
@macroexpand1(@tensor R[a, b] := A[a, c] * B[c, d] * C[d, e] * E[e, f] * F[f, b]),
110+
@macroexpand1(@tensor s = X[a, b] * Y[a, b]),
111+
@macroexpand1(@tensoropt R[a, b] := A[a, c] * B[c, d] * C[d, e] * E[e, b]),
112+
@macroexpand1(@tensor allocator = alloc R[a, b] := A[a, c] * B[c, d] * C[d, b]),
113+
@macroexpand1(@tensor costcheck = warn R[a, b] := A[a, c] * B[c, d] * C[d, b]),
114+
@macroexpand1(@tensor contractcheck = true R[a, b] := A[a, c] * B[c, b]),
118115
]
119116
for ex in exprs
120-
@test isempty(pkglnns(collectlinenumbernodes(ex)))
117+
@test isempty(statementlinenumbernodes(ex))
121118
end
122119
end
123120

124-
@testset "user LineNumberNodes are preserved per statement" begin
125-
# multi-statement block, including a nested contraction whose intermediate is reused
126-
block = @macroexpand @tensor begin
121+
@testset "one user LineNumberNode per statement of a block" begin
122+
# multi-statement block, including a scalar assignment; `s = ...` additionally
123+
# exercises the `_flatten` path that hoists a block into the right hand side
124+
firstline = @__LINE__() + 2
125+
block = @macroexpand1 @tensor begin
127126
T[a, e] := A[a, c] * B[c, d] * C[d, e]
128127
D[a, b] := T[a, e] * E[e, b]
129128
s = D[a, b] * F[a, b]
130129
end
131-
lnns = collectlinenumbernodes(block)
132-
@test isempty(pkglnns(lnns))
133-
@test length(userlines(lnns)) >= 3 # one distinct user line per statement
130+
lnns = statementlinenumbernodes(block)
131+
@test all(l -> l.file === thisfile, lnns)
132+
@test sort!(unique(l.line for l in lnns)) == collect(firstline .+ (0:2))
133+
134+
# dst-reuse: `tensorify` wraps this in a `quote` of its own
135+
reuseline = @__LINE__() + 2
136+
reuseblock = @macroexpand1 @tensor begin
137+
T[a, b] := A[a, c] * B[c, b]
138+
T[a, b] := T[a, c] * C[c, b]
139+
end
140+
reuselnns = statementlinenumbernodes(reuseblock)
141+
@test all(l -> l.file === thisfile, reuselnns)
142+
@test sort!(unique(l.line for l in reuselnns)) == collect(reuseline .+ (0:1))
134143

135-
optblock = @macroexpand @tensoropt begin
144+
optline = @__LINE__() + 2
145+
optblock = @macroexpand1 @tensoropt begin
136146
T[a, e] := A[a, c] * B[c, d] * C[d, e]
137147
D[a, b] := T[a, e] * E[e, b]
138148
end
139-
optlnns = collectlinenumbernodes(optblock)
140-
@test isempty(pkglnns(optlnns))
141-
@test length(userlines(optlnns)) >= 2
149+
optlnns = statementlinenumbernodes(optblock)
150+
@test all(l -> l.file === thisfile, optlnns)
151+
@test sort!(unique(l.line for l in optlnns)) == collect(optline .+ (0:1))
152+
end
153+
154+
@testset "kwargs that generate extra code preserve user line numbers" begin
155+
# `allocator` inserts a checkpoint `quote`, `costcheck` inserts a `@notensor` block
156+
# containing a `@warn` whose own `LineNumberNode` is structurally required
157+
allocline = @__LINE__() + 2
158+
allocblock = @macroexpand1 @tensor allocator = alloc begin
159+
T[a, b] := A[a, c] * B[c, b]
160+
Z[a, b] := T[a, c] * C[c, b]
161+
end
162+
alloclnns = statementlinenumbernodes(allocblock)
163+
@test all(l -> l.file === thisfile, alloclnns)
164+
@test sort!(unique(l.line for l in alloclnns)) == collect(allocline .+ (0:1))
165+
166+
costline = @__LINE__() + 2
167+
costblock = @macroexpand1 @tensor costcheck = warn begin
168+
T[a, b] := A[a, c] * B[c, b]
169+
Z[a, b] := T[a, c] * C[c, b]
170+
end
171+
costlnns = statementlinenumbernodes(costblock)
172+
@test all(l -> l.file === thisfile, costlnns)
173+
@test sort!(unique(l.line for l in costlnns)) == collect(costline .+ (0:1))
174+
# the `@warn` macrocall must have kept its (TensorOperations-internal) LineNumberNode,
175+
# otherwise the expression cannot be expanded at all
176+
@test macroexpand(@__MODULE__, costblock; recursive = true) isa Expr
142177
end
143178
end
144179

‎test/runtests.jl‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,24 @@ using TensorOperations: DefaultAllocator, ManualAllocator, BufferAllocator
1111
precision(::Type{<:Union{Float32, Complex{Float32}}}) = 1.0e-2
1212
precision(::Type{<:Union{Float64, Complex{Float64}}}) = 1.0e-8
1313

14+
# https://github.com/QuantumKitHub/TensorOperations.jl/issues/280: the generated code has to
15+
# keep the user's `LineNumberNode`s -- Julia only emits a coverage counter for lines that a
16+
# `LineNumberNode` points at -- and drop the ones synthesized by the parser, which would
17+
# otherwise re-attribute the statements that follow them to a line in TensorOperations itself.
18+
# Only `LineNumberNode`s in block-statement position matter for that: elsewhere (most notably
19+
# the mandatory 2nd argument of a `:macrocall`) they are structurally required and left alone.
20+
function statementlinenumbernodes(ex, acc = LineNumberNode[])
21+
if ex isa Expr
22+
if ex.head === :block
23+
for e in ex.args
24+
e isa LineNumberNode && push!(acc, e)
25+
end
26+
end
27+
foreach(e -> statementlinenumbernodes(e, acc), ex.args)
28+
end
29+
return acc
30+
end
31+
1432
# don't run all tests on GPU, only the GPU
1533
# specific ones
1634
is_buildkite = get(ENV, "BUILDKITE", "false") == "true"

0 commit comments

Comments
 (0)