Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support begin/end indexing of SourceFile #201

Merged
merged 3 commits into from
Feb 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/source_files.jl
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ function Base.getindex(source::SourceFile, i::Int)
source.code[i]
end

Base.firstindex(source::SourceFile) = firstindex(source.code)
Base.lastindex(source::SourceFile) = lastindex(source.code)

"""
sourcetext(source::SourceFile)

Expand Down
10 changes: 10 additions & 0 deletions test/source_files.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,14 @@
@test source_location(SourceFile(; filename=path), 1) == (1,1)
@test source_location(SourceFile(; filename=path, first_line=7), 1) == (7,1)
end

@test SourceFile("a\nb\n")[1:2] == "a\n"
@test SourceFile("a\nb\n")[3:end] == "b\n"
if Base.VERSION >= v"1.4"
# Protect the `[begin` from being viewed by the parser on older Julia versions
@test eval(Meta.parse("""SourceFile("a\nb\n")[begin:end]""")) == "a\nb\n"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hehehe we are the parser!

So we can almost use JuliaSyntax.parse(Expr, """SourceFile("a\nb\n")[begin:end]""", version=v"1.6") unconditionally here.

But alas, lowering won't understand the result with the begin embedded in the Expr... so not really 😅

Copy link
Sponsor Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is indeed quite ironic! I guess if this were to swap itself in as the include parser, then even older Julia versions would be prepared for this. But given the necessary changes in JuliaLang/julia#46372, presumably this won't happen.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JuliaSyntax.enable_in_core!() does make it work with include()!

But only in Julia 1.6+ because it requires the hooks implemented in JuliaLang/julia#35243

end

# unicode
@test SourceFile("αβ")[1:2] == "α"
end