OpenCores
URL https://opencores.org/ocsvn/tcp_socket/tcp_socket/trunk

Subversion Repositories tcp_socket

[/] [tcp_socket/] [trunk/] [chips2/] [chips/] [compiler/] [tokens.py] - Blame information for rev 4

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 jondawson
__author__ = "Jon Dawson"
2
__copyright__ = "Copyright (C) 2012, Jonathan P Dawson"
3
__version__ = "0.1"
4
 
5
import os.path
6
import StringIO
7
 
8
from chips.compiler.exceptions import C2CHIPError
9
from chips.compiler.builtins import builtins
10 4 jondawson
from chips.compiler.library import libs
11 2 jondawson
 
12
operators = [
13
  "!", "~", "+", "-", "*", "/", "//", "%", "=", "==", "<", ">", "<=", ">=",
14 4 jondawson
  "!=", "|", "&", "^", "||", "&&", "(", ")", "{", "}", "[", "]", ";", "<<",
15
  ">>", ",", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "<<=", ">>=", "^=",
16
  "++", "--", "?", ":", "."
17 2 jondawson
]
18
 
19
class Tokens:
20
 
21 4 jondawson
    """Break the input file into a stream of tokens,
22 2 jondawson
    provide functions to traverse the stream."""
23
 
24
    def __init__(self, filename):
25 4 jondawson
        self.tokens = []
26
        self.filename = None
27
        self.lineno = None
28
        self.scan("built in", StringIO.StringIO(builtins))
29
        self.scan(filename)
30 2 jondawson
 
31
    def scan(self, filename, input_file=None):
32 4 jondawson
 
33 2 jondawson
        """Convert the test file into tokens"""
34
        self.filename = filename
35 4 jondawson
 
36 2 jondawson
        if input_file is None:
37
            try:
38 4 jondawson
                input_file = open(self.filename)
39 2 jondawson
            except IOError:
40
                raise C2CHIPError("Cannot open file: "+self.filename)
41 4 jondawson
 
42 2 jondawson
        token = []
43
        tokens = []
44
        self.lineno = 1
45
        for line in input_file:
46 4 jondawson
 
47 2 jondawson
            #include files
48
            line = line+" "
49
            if line.strip().startswith("#include"):
50
                filename = self.filename
51
                lineno = self.lineno
52
                self.tokens.extend(tokens)
53
                directory = os.path.abspath(self.filename)
54
                directory = os.path.dirname(directory)
55 4 jondawson
                if line.strip().endswith(">"):
56
                    self.filename = "library"
57
                    library = line.strip().split("<")[1].strip(' ><"')
58
                    self.scan(self.filename, StringIO.StringIO(libs[library]))
59
                else:
60
                    self.filename = line.strip().replace("#include", "").strip(' ><"')
61
                    self.filename = os.path.join(directory, self.filename)
62
                    self.scan(self.filename)
63 2 jondawson
                self.lineno = lineno
64
                self.filename = filename
65
                tokens = []
66 4 jondawson
                continue
67
 
68 2 jondawson
            newline = True
69
            for char in line:
70 4 jondawson
 
71 2 jondawson
                if not token:
72
                    token = char
73 4 jondawson
 
74 2 jondawson
                #c style comment
75
                elif (token + char).startswith("/*"):
76
                    if (token + char).endswith("*/"):
77
                        token = ""
78
                    else:
79
                        token += char
80 4 jondawson
 
81 2 jondawson
                #c++ style comment
82
                elif token.startswith("//"):
83
                    if newline:
84
                        token = char
85
                    else:
86
                        token += char
87 4 jondawson
 
88 2 jondawson
                #identifier
89
                elif token[0].isalpha():
90
                    if char.isalnum() or char== "_":
91
                        token += char
92
                    else:
93
                        tokens.append((self.filename, self.lineno, token))
94
                        token = char
95 4 jondawson
 
96 2 jondawson
                #number
97
                elif token[0].isdigit():
98 4 jondawson
                    if char.upper() in "UXABCDEFL0123456789.":
99 2 jondawson
                        token += char
100
                    else:
101
                        tokens.append((self.filename, self.lineno, token))
102
                        token = char
103
 
104
                #string literal
105
                elif token.startswith('"'):
106
                    if char == '"' and previous_char != "\\":
107
                        token += char
108
                        tokens.append((self.filename, self.lineno, token))
109
                        token = ""
110
                    else:
111
                        #remove dummy space from the end of a line
112
                        if newline:
113
                            token = token[:-1]
114
                        previous_char = char
115
                        token += char
116
 
117
                #character literal
118
                elif token.startswith("'"):
119
                    if char == "'":
120
                        token += char
121
                        tokens.append((self.filename, self.lineno, token))
122
                        token = ""
123
                    else:
124
                        token += char
125 4 jondawson
 
126 2 jondawson
                #operator
127
                elif token in operators:
128
                    if token + char in operators:
129
                        token += char
130
                    else:
131
                        tokens.append((self.filename, self.lineno, token))
132
                        token = char
133 4 jondawson
 
134 2 jondawson
                else:
135
                    token = char
136 4 jondawson
 
137 2 jondawson
                newline = False
138
            self.lineno += 1
139 4 jondawson
 
140 2 jondawson
        self.tokens.extend(tokens)
141
 
142
    def error(self, string):
143 4 jondawson
 
144 2 jondawson
        """Generate an error message (including the filename and line number)"""
145 4 jondawson
 
146 2 jondawson
        raise C2CHIPError(string + "\n", self.filename, self.lineno)
147 4 jondawson
 
148 2 jondawson
    def peek(self):
149 4 jondawson
 
150 2 jondawson
        """Return the next token in the stream, but don't consume it"""
151 4 jondawson
 
152 2 jondawson
        if self.tokens:
153
            return self.tokens[0][2]
154
        else:
155
            return ""
156 4 jondawson
 
157 2 jondawson
    def get(self):
158 4 jondawson
 
159 2 jondawson
        """Return the next token in the stream, and consume it"""
160 4 jondawson
 
161 2 jondawson
        if self.tokens:
162
            self.lineno = self.tokens[0][1]
163
            self.filename = self.tokens[0][0]
164
        filename, lineno, token = self.tokens.pop(0)
165
        return token
166 4 jondawson
 
167 2 jondawson
    def end(self):
168 4 jondawson
 
169 2 jondawson
        """Return True if all the tokens have been consumed"""
170 4 jondawson
 
171 2 jondawson
        return not self.tokens
172 4 jondawson
 
173 2 jondawson
    def expect(self, expected):
174 4 jondawson
 
175
        """Consume the next token in the stream,
176 2 jondawson
        generate an error if it is not as expected."""
177 4 jondawson
 
178 2 jondawson
        filename, lineno, actual = self.tokens.pop(0)
179
        if self.tokens:
180
            self.lineno = self.tokens[0][1]
181
            self.filename = self.tokens[0][0]
182
        if actual == expected:
183
            return
184
        else:
185
            self.error("Expected: %s, got: %s"%(expected, actual))

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.