source: proto/matchparens/parenmatch2.py @ 3031

Last change on this file since 3031 was 3031, checked in by cameron, 6 years ago

More tightening of paren match prototypes

File size: 1.9 KB
Line 
1#
2# Recursive Parenthesis Matching
3#
4#
5# Robert D. Cameron
6# October 14, 2012
7#
8import sys
9import pablo
10
11class Basis_bits():     
12        bit_0 = 0
13        bit_1 = 0
14        bit_2 = 0
15        bit_3 = 0
16        bit_4 = 0
17        bit_5 = 0
18        bit_6 = 0
19        bit_7 = 0
20
21class Lex ():
22        LParen = 0
23        RParen = 0
24       
25class Matches() :
26        closed = {}
27        error = 0
28
29
30def Classify_bytes(basis_bits, lex): 
31        temp1 = (basis_bits.bit_0 | basis_bits.bit_1)
32        temp2 = (basis_bits.bit_2 &~ basis_bits.bit_3)
33        temp3 = (temp2 &~ temp1)
34        temp4 = (basis_bits.bit_4 &~ basis_bits.bit_5)
35        temp5 = (basis_bits.bit_6 | basis_bits.bit_7)
36        temp6 = (temp4 &~ temp5)
37        lex.LParen = (temp3 & temp6)
38        temp7 = (basis_bits.bit_7 &~ basis_bits.bit_6)
39        temp8 = (temp4 & temp7)
40        lex.RParen = (temp3 & temp8)
41       
42def Match_Parens(lex, matches):
43        parens = lex.LParen | lex.RParen
44        Lscan = pablo.AdvanceThenScanTo(lex.LParen, parens)
45        Rscan = pablo.AdvanceThenScanTo(lex.RParen, parens)
46        matches.closed = Lscan & lex.RParen
47        matches.error = pablo.atEOF(Lscan)
48        unclosed = Lscan & lex.LParen | Rscan & lex.RParen
49        while unclosed:
50                unclosedLParen = unclosed & lex.LParen
51                unclosedRParen = unclosed & lex.RParen
52                Lscan = pablo.AdvanceThenScanTo(unclosedLParen, unclosed)
53                Rscan = pablo.AdvanceThenScanTo(unclosedRParen, unclosed)
54                matches.closed |= Lscan & lex.RParen
55                matches.error |= pablo.atEOF(Lscan)
56                unclosed = Lscan & lex.LParen | Rscan & lex.RParen
57        #
58        # Any closing paren that was not actually used to close
59        # an opener is in error.
60        matches.error |= lex.RParen &~ matches.closed
61
62
63basis_bits = Basis_bits()
64lex = Lex()
65matches = Matches()
66
67if __name__ == "__main__":
68        #print "Starting ..."
69        if len(sys.argv) > 1:
70                u8data = pablo.readfile(sys.argv[1]) 
71                pablo.EOF_mask = pablo.transpose_streams(u8data, basis_bits)
72                Classify_bytes(basis_bits, lex)
73                Match_Parens(lex, matches)
74                lgth = len(u8data)
75                print "data:" + " "*(16-5) + u8data
76                print "errors" + " "*(16-6) + pablo.bitstream2string(matches.error, lgth+1)
77               
78        else:
79                print("Usage: python parenmatch.py <file>")
80       
81
82
Note: See TracBrowser for help on using the repository browser.