-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdsl_parser.py
More file actions
executable file
·39 lines (29 loc) · 1.09 KB
/
dsl_parser.py
File metadata and controls
executable file
·39 lines (29 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
##################################################################
# This section of code taken directly from Peter Norvig's lis.py #
# https://norvig.com/lispy.html #
##################################################################
from typing import NewType
def dsl_parse(src_str: str):
"Converts a scheme expression into a string"
return read_from_tokens(tokenize(src_str))
def tokenize(s):
"Convert a string into a list of tokens."
return s.replace('(', ' ( ').replace(')', ' ) ').split()
def read_from_tokens(tokens: list):
"Read an expression from a sequence of tokens."
if len(tokens) == 0:
raise SyntaxError('unexpected EOF')
token = tokens.pop(0)
if token == '(':
L = []
while tokens[0] != ')':
L.append(read_from_tokens(tokens))
tokens.pop(0) # pop off ')'
return tuple(L)
elif token == ')':
raise SyntaxError('unexpected )')
else:
return atom(token)
def atom(token: str):
"Numbers become numbers; every other token is a symbol."
return str(token)