Skip to content

Commit 270ac21

Browse files
committed
Added typing.
Moved constants into a separate enum. Reformatted with black and autopep8. Now it uses LF line endings and tabs.
1 parent 9b5a18d commit 270ac21

18 files changed

+5241
-5452
lines changed

.editorconfig

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,4 @@ charset = utf-8
44
indent_style = tab
55
indent_size = 4
66
insert_final_newline = true
7-
8-
[*.{py,frame}]
9-
charset = utf-8
10-
indent_style = space
11-
indent_size = 3
12-
insert_final_newline = true
7+
newline = lf

Coco/CLI.py

Lines changed: 30 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,90 +1,36 @@
1+
from typing import List
12
import plumbum.cli
23

4+
35
class ApplicationWithArgsParsing(plumbum.cli.Application):
4-
@classmethod
5-
def parseArgs(cls, args):
6-
s=cls("")
7-
validators, restOfArgs=s._validate_args(*s._parse_args(args))
8-
for validator, args in validators:
9-
validator(s, *args)
10-
return s
6+
@classmethod
7+
def parseArgs(cls, args: List[str]) -> "CocoArgs":
8+
s = cls("")
9+
validators, restOfArgs = s._validate_args(*s._parse_args(args))
10+
for validator, args in validators:
11+
validator(s, *args)
12+
return s
13+
1114

1215
class CocoArgs(ApplicationWithArgsParsing):
13-
traceAutomaton=plumbum.cli.Flag(
14-
('a', 'A', "traceAutomaton"),
15-
help='Include automaton tracing in the trace file.',
16-
default=False
17-
)
18-
generateDriver=plumbum.cli.Flag(
19-
('c', 'C', "generateDriver"),
20-
help='Generate a main compiler source file.',
21-
default=False
22-
)
23-
firstAndFollow=plumbum.cli.Flag(
24-
('f', 'F', "firstAndFollow"),
25-
default=False,
26-
help='Include first & follow sets in the trace file.'
27-
)
28-
syntaxGraph=plumbum.cli.Flag(
29-
('g', 'G', "syntaxGraph"),
30-
default=False,
31-
help='Include syntax graph in the trace file.'
32-
)
33-
traceComputations=plumbum.cli.Flag(
34-
('i', 'I', "traceComputations"),
35-
default=False,
36-
help='Include a trace of the computations for first sets in the trace file.'
37-
)
38-
listAnyAndSync=plumbum.cli.Flag(
39-
('j', 'J', "listAnyAndSync"),
40-
default=False,
41-
help='Inclue a listing of the ANY and SYNC sets in the trace file.'
42-
)
43-
mergeErrors=plumbum.cli.Flag(
44-
('m', 'M', "mergeErrors"),
45-
default=False,
46-
help='Merge error messages in the source listing.'
47-
)
48-
tokenNames=plumbum.cli.Flag(
49-
('n', 'N', "tokenNames"),
50-
default=False,
51-
help='Generate token names in the source listing.'
52-
)
53-
statistics=plumbum.cli.Flag(
54-
('-p', '-P', "statistics"),
55-
default=False,
56-
help='Include a listing of statistics in the trace file.'
57-
)
58-
frameFileDir=plumbum.cli.SwitchAttr(
59-
('-r', '-R', "frameFileDir"),
60-
plumbum.cli.ExistingDirectory,
61-
default=False,
62-
help='Use scanner.frame and parser.frame in this directory.'
63-
)
64-
symbolTable=plumbum.cli.Flag(
65-
('-s', '-S', "symbolTable"),
66-
default=False,
67-
help='Include the symbol table listing in the trace file.'
68-
)
69-
testOnly=plumbum.cli.Flag(
70-
('-t', '-T', "testOnly"),
71-
default=False,
72-
help='Test the grammar only, don\'t generate any files.'
73-
)
74-
crossReferences=plumbum.cli.Flag(
75-
('-x', '-X', "xref"),
76-
default=False,
77-
help='Include a cross reference listing in the trace file.'
78-
)
79-
80-
outputDir=plumbum.cli.SwitchAttr(
81-
('-O', "outputDir"),
82-
plumbum.cli.ExistingDirectory,
83-
default=False,
84-
help='Output files to that directory.'
85-
)
86-
87-
def main(self, *args, **kwargs):
88-
return self
16+
traceAutomaton = plumbum.cli.Flag(("a", "A", "traceAutomaton"), help="Include automaton tracing in the trace file.", default=False)
17+
generateDriver = plumbum.cli.Flag(("c", "C", "generateDriver"), help="Generate a main compiler source file.", default=False)
18+
firstAndFollow = plumbum.cli.Flag(("f", "F", "firstAndFollow"), default=False, help="Include first & follow sets in the trace file.")
19+
syntaxGraph = plumbum.cli.Flag(("g", "G", "syntaxGraph"), default=False, help="Include syntax graph in the trace file.")
20+
traceComputations = plumbum.cli.Flag(("i", "I", "traceComputations"), default=False, help="Include a trace of the computations for first sets in the trace file.")
21+
listAnyAndSync = plumbum.cli.Flag(("j", "J", "listAnyAndSync"), default=False, help="Inclue a listing of the ANY and SYNC sets in the trace file.")
22+
mergeErrors = plumbum.cli.Flag(("m", "M", "mergeErrors"), default=False, help="Merge error messages in the source listing.")
23+
tokenNames = plumbum.cli.Flag(("n", "N", "tokenNames"), default=False, help="Generate token names in the source listing.")
24+
statistics = plumbum.cli.Flag(("-p", "-P", "statistics"), default=False, help="Include a listing of statistics in the trace file.")
25+
frameFileDir = plumbum.cli.SwitchAttr(("-r", "-R", "frameFileDir"), plumbum.cli.ExistingDirectory, default=False, help="Use scanner.frame and parser.frame in this directory.")
26+
symbolTable = plumbum.cli.Flag(("-s", "-S", "symbolTable"), default=False, help="Include the symbol table listing in the trace file.")
27+
testOnly = plumbum.cli.Flag(("-t", "-T", "testOnly"), default=False, help="Test the grammar only, don't generate any files.")
28+
crossReferences = plumbum.cli.Flag(("-x", "-X", "xref"), default=False, help="Include a cross reference listing in the trace file.")
29+
30+
outputDir = plumbum.cli.SwitchAttr(("-O", "outputDir"), plumbum.cli.ExistingDirectory, default=False, help="Output files to that directory.")
31+
32+
def main(self, *args, **kwargs):
33+
return self
34+
8935

90-
parseArgs=CocoArgs.parseArgs
36+
parseArgs = CocoArgs.parseArgs

Coco/CharClass.py

Lines changed: 73 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -27,81 +27,84 @@
2727
#-------------------------------------------------------------------------
2828
from .Trace import Trace
2929

30-
class CharClass( object ):
31-
classes = [ ]
32-
dummyName = ord('A')
30+
from typing import Optional, Set, Union
3331

34-
charSetSize = 256 # must be a multiple of 16
3532

36-
def __init__( self, name, s ):
37-
assert isinstance( name, str )
38-
assert isinstance( s, set )
39-
if name == "#":
40-
name = "#" + chr(__class__.dummyName)
41-
self.__class__.dummyName += 1
42-
self.n = len(__class__.classes) # class number
43-
self.name = name # class name
44-
self.set = s # set representing the class
45-
self.__class__.classes.append(self)
33+
class CharClass(object):
34+
classes = []
35+
dummyName = ord("A")
4636

47-
@staticmethod
48-
def Find( nameOrSet ):
49-
assert isinstance( nameOrSet, (str, set) )
50-
if isinstance(nameOrSet,str):
51-
name = nameOrSet
52-
for c in __class__.classes:
53-
if c.name == name:
54-
return c
55-
return None
56-
else:
57-
s = nameOrSet
58-
for c in __class__.classes:
59-
if s == c.set: #Sets.Equals(s, c.set):
60-
return c
61-
return None
37+
charSetSize = 256 # must be a multiple of 16
6238

63-
@staticmethod
64-
def Set( i ):
65-
assert isinstance( i, int )
66-
return __class__.classes[i].set
39+
def __init__(self, name: str, s: Union[Set[int], Set[Union[int, str]]]) -> None:
40+
assert isinstance(name, str)
41+
assert isinstance(s, set)
42+
if name == "#":
43+
name = "#" + chr(__class__.dummyName)
44+
self.__class__.dummyName += 1
45+
self.n = len(__class__.classes) # class number
46+
self.name = name # class name
47+
self.set = s # set representing the class
48+
self.__class__.classes.append(self)
6749

68-
@staticmethod
69-
def Ch( ch ):
70-
assert isinstance( ch, str ) or isinstance( ch, int )
71-
if isinstance( ch, str ):
72-
ch = ord(ch)
73-
if ch < ord(' ') or ch >= 127 or ch == ord('\'') or ch == ord('\\'):
74-
return str(ch)
75-
else:
76-
return "'" + chr(ch) + "'"
50+
@staticmethod
51+
def Find(nameOrSet: Union[Set[int], str]) -> Optional["CharClass"]:
52+
assert isinstance(nameOrSet, (str, set))
53+
if isinstance(nameOrSet, str):
54+
name = nameOrSet
55+
for c in __class__.classes:
56+
if c.name == name:
57+
return c
58+
return None
59+
else:
60+
s = nameOrSet
61+
for c in __class__.classes:
62+
if s == c.set: # Sets.Equals(s, c.set):
63+
return c
64+
return None
7765

78-
@staticmethod
79-
def WriteClasses( ):
80-
for c in __class__.classes:
81-
Trace.Write(str(c.name), -10)
82-
Trace.Write(': ')
83-
c.WriteSet( )
84-
Trace.WriteLine()
85-
Trace.WriteLine()
66+
@staticmethod
67+
def Set(i: int) -> Union[Set[int], Set[Union[int, str]]]:
68+
assert isinstance(i, int)
69+
return __class__.classes[i].set
8670

87-
def WriteSet( self ):
88-
s = self.set.copy()
89-
try:
90-
s.remove('ANYCHAR')
91-
except KeyError:
92-
pass
71+
@staticmethod
72+
def Ch(ch):
73+
assert isinstance(ch, str) or isinstance(ch, int)
74+
if isinstance(ch, str):
75+
ch = ord(ch)
76+
if ch < ord(" ") or ch >= 127 or ch == ord("'") or ch == ord("\\"):
77+
return str(ch)
78+
else:
79+
return "'" + chr(ch) + "'"
9380

94-
i = 0
95-
mx = max(s) + 1
96-
while i < mx:
97-
while i < mx and (i not in s):
98-
i += 1
99-
if i == mx:
100-
break
101-
j = i
102-
while i < mx and (i in s):
103-
i += 1
104-
if j < (i - 1):
105-
Trace.Write(str(self.__class__.Ch(j)) + ".." + str(self.__class__.Ch(i-1)) + " ")
106-
else:
107-
Trace.Write(str(self.__class__.Ch(j) + " "))
81+
@staticmethod
82+
def WriteClasses():
83+
for c in __class__.classes:
84+
Trace.Write(str(c.name), -10)
85+
Trace.Write(": ")
86+
c.WriteSet()
87+
Trace.WriteLine()
88+
Trace.WriteLine()
89+
90+
def WriteSet(self):
91+
s = self.set.copy()
92+
try:
93+
s.remove("ANYCHAR")
94+
except KeyError:
95+
pass
96+
97+
i = 0
98+
mx = max(s) + 1
99+
while i < mx:
100+
while i < mx and (i not in s):
101+
i += 1
102+
if i == mx:
103+
break
104+
j = i
105+
while i < mx and (i in s):
106+
i += 1
107+
if j < (i - 1):
108+
Trace.Write(str(self.__class__.Ch(j)) + ".." + str(self.__class__.Ch(i - 1)) + " ")
109+
else:
110+
Trace.Write(str(self.__class__.Ch(j) + " "))

0 commit comments

Comments
 (0)