Last active
March 4, 2024 23:40
-
-
Save TorsteinOvstedal/85927925b4070aa1a9e2a66511575443 to your computer and use it in GitHub Desktop.
Example usage of a State Transition Table. Checks if the input string has the form of a valid unsigned integer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
State transition table for scanning an unsigned int. | |
Source: p. 34, Engineering a Compiler, 3ed. | |
""" | |
S0 = 0 | |
S1 = 1 | |
S2 = 2 | |
SE = 3 | |
table = [ | |
[S1, S2, S2, S2, S2, S2, S2, S2, S2, S2], | |
[SE, SE, SE, SE, SE, SE, SE, SE, SE, SE], | |
[S2, S2, S2, S2, S2, S2, S2, S2, S2, S2], | |
[SE, SE, SE, SE, SE, SE, SE, SE, SE, SE], | |
] | |
def next_state(state, char): | |
index = ord(char) - ord("0") | |
if index >= 0 and index <= 9: | |
return table[state][index] | |
else: | |
return SE | |
def print_error(string, state, cursor): | |
column = cursor - 1 | |
print(f"Error: Unexpected symbol at column {column}.") | |
print(f"{string}\n{'^'.rjust(column)}") | |
def is_uint(string): | |
buffer = string + "\0" | |
cursor = 0 | |
state = S0 | |
char = buffer[cursor]; cursor += 1 | |
while state != SE and char != '\0': | |
state = next_state(state, char) | |
char = buffer[cursor]; cursor += 1 | |
if state == S1 or state == S2: | |
return True | |
else: | |
print_error(string, state, cursor) | |
return False | |
assert is_uint("0") | |
assert is_uint("00") == False | |
assert is_uint("09") == False | |
assert is_uint("1") | |
assert is_uint("1325982034852000394500") | |
assert is_uint("13259823485239?45") == False | |
assert is_uint("Hello World") == False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment