86 lines
1.6 KiB
Python
86 lines
1.6 KiB
Python
"""
|
|
Utility functions used for parsing.
|
|
"""
|
|
|
|
|
|
def can_be_mark(argument):
|
|
"""
|
|
The ``argument`` can be interpreted as a Mark.
|
|
"""
|
|
a = ord("a")
|
|
a_z = [chr(a + i) for i in range(26)]
|
|
A = ord("A")
|
|
A_Z = [chr(A + i) for i in range(26)]
|
|
null = ord("0")
|
|
null_9 = [chr(null + i) for i in range(10)]
|
|
|
|
if(not argument[0] in a_z):
|
|
return False
|
|
|
|
for char in argument[1:]:
|
|
if(not (char in a_z
|
|
or char in A_Z
|
|
or char in null_9
|
|
or char == "_")):
|
|
return False
|
|
return True
|
|
|
|
|
|
|
|
def can_convert_to_int(value):
|
|
"""
|
|
``value`` can be converted to an integer.
|
|
|
|
**Note** that this returns ``True`` if the value is a
|
|
character definition like ``'a'``.
|
|
"""
|
|
if(value.startswith("0x")):
|
|
try:
|
|
int(value[2:], 16)
|
|
return True
|
|
except:
|
|
return False
|
|
|
|
if(value.startswith("0b")):
|
|
try:
|
|
int(value[2:], 2)
|
|
return True
|
|
except:
|
|
return False
|
|
|
|
if(value.startswith("'") and value.endswith("'")):
|
|
if(len(value) == 3):
|
|
return True
|
|
if(len(value) == 4):
|
|
if(value[1:-1] in {"\\n", "\\r", "\\t"}):
|
|
return True
|
|
return False
|
|
|
|
try:
|
|
int(value)
|
|
return True
|
|
except:
|
|
return False
|
|
|
|
def autoint(value):
|
|
"""
|
|
Convert ``value`` to an integer automatically.
|
|
"""
|
|
escape_sequences = {"\\n": "\n", "\\r": "\r", "\\t":"\t"}
|
|
if(value.startswith("0x")):
|
|
return int(value[2:], 16)
|
|
|
|
if(value.startswith("0b")):
|
|
return int(value[2:], 2)
|
|
|
|
if(value.startswith("'") and value.endswith("'")):
|
|
if(len(value) == 3):
|
|
return ord(value[1:-1])
|
|
if(len(value) == 4):
|
|
if(value[1:-1] in escape_sequences):
|
|
return ord(escape_sequences[value[1:-1]])
|
|
|
|
return int(value)
|
|
|
|
|