|
| 1 | +""":func:`~pandas.eval` source string parsing functions |
| 2 | +""" |
| 3 | + |
| 4 | +from io import StringIO |
| 5 | +from keyword import iskeyword |
| 6 | +import token |
| 7 | +import tokenize |
| 8 | +from typing import Iterator, Tuple |
| 9 | + |
| 10 | +# A token value Python's tokenizer probably will never use. |
| 11 | +BACKTICK_QUOTED_STRING = 100 |
| 12 | + |
| 13 | +Tok = Tuple[int, str] |
| 14 | + |
| 15 | + |
| 16 | +def create_valid_python_identifier(name: str) -> str: |
| 17 | + """ |
| 18 | + Create valid Python identifiers from any string. |
| 19 | +
|
| 20 | + Check if name contains any special characters. If it contains any |
| 21 | + special characters, the special characters will be replaced by |
| 22 | + a special string and a prefix is added. |
| 23 | +
|
| 24 | + Raises |
| 25 | + ------ |
| 26 | + If the returned name is not a Python valid identifier, raise an exception. |
| 27 | + This can happen if there is a hashtag in the name, as the tokenizer will |
| 28 | + than terminate and not find the backtick. |
| 29 | + But also for characters that fall out of the range of (U+0001..U+007F). |
| 30 | + """ |
| 31 | + if name.isidentifier() and not iskeyword(name): |
| 32 | + return name |
| 33 | + |
| 34 | + # Create a dict with the special characters and their replacement string. |
| 35 | + # EXACT_TOKEN_TYPES contains these special characters |
| 36 | + # toke.tok_name contains a readable description of the replacement string. |
| 37 | + special_characters_replacements = { |
| 38 | + char: f"_{token.tok_name[tokval]}_" |
| 39 | + # The ignore here is because of a bug in mypy that is resolved in 0.740 |
| 40 | + for char, tokval in tokenize.EXACT_TOKEN_TYPES.items() # type: ignore |
| 41 | + } |
| 42 | + special_characters_replacements.update( |
| 43 | + { |
| 44 | + " ": "_", |
| 45 | + "?": "_QUESTIONMARK_", |
| 46 | + "!": "_EXCLAMATIONMARK_", |
| 47 | + "$": "_DOLLARSIGN_", |
| 48 | + "€": "_EUROSIGN_", |
| 49 | + # Including quotes works, but there are exceptions. |
| 50 | + "'": "_SINGLEQUOTE_", |
| 51 | + '"': "_DOUBLEQUOTE_", |
| 52 | + # Currently not possible. Terminates parser and won't find backtick. |
| 53 | + # "#": "_HASH_", |
| 54 | + } |
| 55 | + ) |
| 56 | + |
| 57 | + name = "".join(special_characters_replacements.get(char, char) for char in name) |
| 58 | + name = "BACKTICK_QUOTED_STRING_" + name |
| 59 | + |
| 60 | + if not name.isidentifier(): |
| 61 | + raise SyntaxError(f"Could not convert '{name}' to a valid Python identifier.") |
| 62 | + |
| 63 | + return name |
| 64 | + |
| 65 | + |
| 66 | +def clean_backtick_quoted_toks(tok: Tok) -> Tok: |
| 67 | + """ |
| 68 | + Clean up a column name if surrounded by backticks. |
| 69 | +
|
| 70 | + Backtick quoted string are indicated by a certain tokval value. If a string |
| 71 | + is a backtick quoted token it will processed by |
| 72 | + :func:`_create_valid_python_identifier` so that the parser can find this |
| 73 | + string when the query is executed. |
| 74 | + In this case the tok will get the NAME tokval. |
| 75 | +
|
| 76 | + Parameters |
| 77 | + ---------- |
| 78 | + tok : tuple of int, str |
| 79 | + ints correspond to the all caps constants in the tokenize module |
| 80 | +
|
| 81 | + Returns |
| 82 | + ------- |
| 83 | + t : tuple of int, str |
| 84 | + Either the input or token or the replacement values |
| 85 | + """ |
| 86 | + toknum, tokval = tok |
| 87 | + if toknum == BACKTICK_QUOTED_STRING: |
| 88 | + return tokenize.NAME, create_valid_python_identifier(tokval) |
| 89 | + return toknum, tokval |
| 90 | + |
| 91 | + |
| 92 | +def clean_column_names(name: str) -> str: |
| 93 | + """ |
| 94 | + Function to emulate the cleaning of a backtick quoted name. |
| 95 | +
|
| 96 | + The purpose for this function is to see what happens to the name of |
| 97 | + identifier if it goes to the process of being parsed a Python code |
| 98 | + inside a backtick quoted string and than being cleaned |
| 99 | + (removed of any special characters). |
| 100 | +
|
| 101 | + Returns |
| 102 | + ------- |
| 103 | + Returns the name after tokenizing and cleaning, |
| 104 | + or 'name' if that operation failed. |
| 105 | + """ |
| 106 | + try: |
| 107 | + tokenized = tokenize_string(f"`{name}`") |
| 108 | + tokval = next(tokenized)[1] |
| 109 | + return create_valid_python_identifier(tokval) |
| 110 | + except SyntaxError: |
| 111 | + # Rarely, a name cannot be converted to a valid Python identifier. |
| 112 | + # So, we just return the name. |
| 113 | + # If this name was used in the query string, |
| 114 | + # an error will be raised by :func:`tokenize_backtick_quoted_string` instead |
| 115 | + return name |
| 116 | + |
| 117 | + |
| 118 | +def tokenize_backtick_quoted_string( |
| 119 | + token_generator: Iterator[tokenize.TokenInfo], source: str, string_start: int |
| 120 | +) -> Tok: |
| 121 | + """ |
| 122 | + Creates a token from a backtick quoted string. |
| 123 | +
|
| 124 | + Moves the token_generator forwards till right after the next backtick. |
| 125 | + """ |
| 126 | + for _, tokval, start, _, _ in token_generator: |
| 127 | + if tokval == "`": |
| 128 | + string_end = start[1] |
| 129 | + break |
| 130 | + |
| 131 | + return BACKTICK_QUOTED_STRING, source[string_start:string_end] |
| 132 | + |
| 133 | + |
| 134 | +def tokenize_string(source: str) -> Iterator[Tok]: |
| 135 | + """ |
| 136 | + Tokenize a Python source code string. |
| 137 | +
|
| 138 | + Parameters |
| 139 | + ---------- |
| 140 | + source : str |
| 141 | + A Python source code string |
| 142 | + """ |
| 143 | + line_reader = StringIO(source).readline |
| 144 | + token_generator = tokenize.generate_tokens(line_reader) |
| 145 | + |
| 146 | + # Loop over all tokens till a backtick (`) is found. |
| 147 | + # Then, take all tokens till the next backtick to form a backtick quoted string |
| 148 | + for toknum, tokval, start, _, _ in token_generator: |
| 149 | + if tokval == "`": |
| 150 | + try: |
| 151 | + yield tokenize_backtick_quoted_string( |
| 152 | + token_generator, source, string_start=start[1] + 1 |
| 153 | + ) |
| 154 | + except Exception: |
| 155 | + raise SyntaxError(f"Failed to parse backticks in '{source}'.") |
| 156 | + else: |
| 157 | + yield toknum, tokval |
0 commit comments