| 1 |
import re |
| 2 |
from .errors import ClinicError |
| 3 |
|
| 4 |
|
| 5 |
is_legal_c_identifier = re.compile("^[A-Za-z_][A-Za-z0-9_]*$").match |
| 6 |
|
| 7 |
|
| 8 |
def is_legal_py_identifier(identifier: str) -> bool: |
| 9 |
return all(is_legal_c_identifier(field) for field in identifier.split(".")) |
| 10 |
|
| 11 |
|
| 12 |
# Identifiers that are okay in Python but aren't a good idea in C. |
| 13 |
# So if they're used Argument Clinic will add "_value" to the end |
| 14 |
# of the name in C. |
| 15 |
_c_keywords = frozenset(""" |
| 16 |
asm auto break case char const continue default do double |
| 17 |
else enum extern float for goto if inline int long |
| 18 |
register return short signed sizeof static struct switch |
| 19 |
typedef typeof union unsigned void volatile while |
| 20 |
""".strip().split() |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
def ensure_legal_c_identifier(identifier: str) -> str: |
| 25 |
# For now, just complain if what we're given isn't legal. |
| 26 |
if not is_legal_c_identifier(identifier): |
| 27 |
raise ClinicError(f"Illegal C identifier: {identifier}") |
| 28 |
# But if we picked a C keyword, pick something else. |
| 29 |
if identifier in _c_keywords: |
| 30 |
return identifier + "_value" |
| 31 |
return identifier |