forked from whaleygeek/MyLittleComputer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
77 lines (58 loc) · 1.74 KB
/
parser.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# parser.py 03/11/2014 D.J.Whale
#
# Parse an input program file
import instruction
def labelFromString(s):
"""Work out if this operand is a label or not"""
# Is it numeric?
try:
operand = int(s)
return operand, None # just a normal number
except:
pass
# Must be a label
return None, s # A labelref
def parseLine(line):
"""parse a line into an instruction"""
# Ignore lines that are comments
line = line.strip()
if line.startswith('#'):
return None, None, None, None # whole-line comment
# Strip off end of line comment
try:
commentpos = line.index('#')
line = line[:commentpos]
line = line.strip()
except:
pass
# Ignore lines with no instruction on them
parts = line.split(" ")
if len(parts) == 0: # empty line
return None
# Split line into [label] [operator] [operand]
label = None
operator = None
operand = None
labelref = None
if len(parts) == 1: # (label) or (operator)
if instruction.isOperator(parts[0]): # (operator)
operator = instruction.operatorFromString(parts[0])
else: # (label) (operator)
label = parts[0]
elif len(parts) == 2: # (label operator) or (operator operand)
if instruction.isOperator(parts[0]): # (operator operand)
operator = instruction.operatorFromString(parts[0])
operand, labelref = labelFromString(parts[1])
else: # (label operator)
label = parts[0]
operator = instruction.operatorFromString(parts[1])
elif len(parts) == 3: # (label operator operand)
label = parts[0]
operator = instruction.operatorFromString(parts[1])
operand, labelref = labelFromString(parts[2])
# DAT or instruction?
if operator == instruction.DAT:
operator = operand
operand = None
return label, operator, operand, labelref
# END