Skip to content

Commit 63f9cb4

Browse files
authored
Feat(sqlglotrs): match the Python implementation of __repr__ for tokens (#5172)
1 parent 434c45b commit 63f9cb4

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

sqlglotrs/src/token.rs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::settings::TokenType;
22
use pyo3::prelude::*;
33
use pyo3::types::{PyList, PyString};
4-
use pyo3::{pyclass, Py, PyObject, Python};
4+
use pyo3::{pyclass, pymethods, Py, PyObject, Python};
55

66
#[derive(Debug)]
77
#[pyclass]
@@ -57,3 +57,25 @@ impl Token {
5757
});
5858
}
5959
}
60+
61+
#[pymethods]
62+
impl Token {
63+
fn __repr__(&self, py: Python) -> PyResult<String> {
64+
let text = self.text.bind(py).to_str()?;
65+
let comments = self.comments.bind(py);
66+
let token_type_str = self.token_type_py.bind(py).str()?;
67+
let comments_repr = comments.repr()?;
68+
let comments_str = comments_repr.to_str()?;
69+
70+
Ok(format!(
71+
"<Token token_type: {}, text: {}, line: {}, col: {}, start: {}, end: {}, comments: {}>",
72+
token_type_str,
73+
text,
74+
self.line,
75+
self.col,
76+
self.start,
77+
self.end,
78+
comments_str
79+
))
80+
}
81+
}

tests/test_tokens.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,3 +201,10 @@ def test_partial_token_list(self):
201201
self.assertEqual(len(partial_tokens), 1)
202202
self.assertEqual(partial_tokens[0].token_type, TokenType.VAR)
203203
self.assertEqual(partial_tokens[0].text, "foo")
204+
205+
def test_token_repr(self):
206+
# Ensures both the Python and the Rust tokenizer produce a human-friendly representation
207+
self.assertEqual(
208+
repr(Tokenizer().tokenize("foo")),
209+
"[<Token token_type: TokenType.VAR, text: foo, line: 1, col: 3, start: 0, end: 2, comments: []>]",
210+
)

0 commit comments

Comments
 (0)