Skip to content

Commit

Permalink
feat: Python strings
Browse files Browse the repository at this point in the history
  • Loading branch information
alexpovel committed Dec 2, 2023
1 parent 5970336 commit f452b01
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/scoping/langs/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub type PythonQuery = CodeQuery<CustomPythonQuery, PremadePythonQuery>;
pub enum PremadePythonQuery {
/// Comments.
Comments,
/// Strings (raw, byte, f-strings; interpolation is respected; quotes included).
Strings,
/// Docstrings (not including multi-line strings).
DocStrings,
/// Function names, at the definition site.
Expand All @@ -28,6 +30,17 @@ impl From<PremadePythonQuery> for TSQuery {
Python::lang(),
match value {
PremadePythonQuery::Comments => "(comment) @comment",
PremadePythonQuery::Strings => {
// Match either normal `string`s or `string`s with `interpolation`;
// using only the latter doesn't include the former.
r#"
[
(string)
(string (interpolation) @IGNORE)
]
@string
"#
}
PremadePythonQuery::DocStrings => {
// Triple-quotes are also used for multi-line strings. So look only
// for stand-alone expressions, which are not part of some variable
Expand Down
11 changes: 11 additions & 0 deletions tests/langs/python/in/strings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name = "Ali__T__ce"
ag__T__e = 30
f_string = f"name:__T__ {name}, age: {ag__T__e}__T__"

multiline_f_string = f"""This is a__T__
multiline{f_string} string
spanning several lines__T__"""

raw_string = r"This is a raw string__T__ with no special treatment for \n"
bytes_string = b"This is a bytes__T__ string"
bytes_string = rf"This is a __T__raw f-string with {raw_string}"
1 change: 1 addition & 0 deletions tests/langs/python/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use super::{get_input_output, nuke_target};

#[rstest]
#[case("docstring.py", PythonQuery::Premade(PremadePythonQuery::DocStrings))]
#[case("strings.py", PythonQuery::Premade(PremadePythonQuery::Strings))]
#[case("comments-lf.py", PythonQuery::Premade(PremadePythonQuery::Comments))]
#[case("comments-crlf.py", PythonQuery::Premade(PremadePythonQuery::Comments))]
#[case(
Expand Down
11 changes: 11 additions & 0 deletions tests/langs/python/out/strings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name = "Alice"
ag__T__e = 30
f_string = f"name: {name}, age: {ag__T__e}"

multiline_f_string = f"""This is a
multiline{f_string} string
spanning several lines"""

raw_string = r"This is a raw string with no special treatment for \n"
bytes_string = b"This is a bytes string"
bytes_string = rf"This is a raw f-string with {raw_string}"

0 comments on commit f452b01

Please sign in to comment.