blob: 6de4364d7050f4ee669a126cb5bafe83d777cae1 [file] [log] [blame]
[email protected]cffee7f2013-04-11 17:03:481#!/usr/bin/env python
[email protected]683c8c52013-04-06 17:00:462# Copyright (c) 2013 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Kenichi Ishibashi23e996b2017-06-22 07:16:286""" Lexer for Web IDL
[email protected]683c8c52013-04-06 17:00:467
Kenichi Ishibashi23e996b2017-06-22 07:16:288The lexer uses the PLY library to build a tokenizer which understands
9Web IDL tokens.
[email protected]683c8c52013-04-06 17:00:4610
Kenichi Ishibashi23e996b2017-06-22 07:16:2811Web IDL, and Web IDL regular expressions can be found at:
raphael.kubo.da.costa4bec0d72017-02-22 10:12:4412 http://heycam.github.io/webidl/
[email protected]683c8c52013-04-06 17:00:4613PLY can be found at:
14 http://www.dabeaz.com/ply/
15"""
16
[email protected]683c8c52013-04-06 17:00:4617import os.path
18import sys
19
raphael.kubo.da.costaadf05592017-02-21 12:58:2320SRC_DIR = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
21sys.path.insert(0, os.path.join(SRC_DIR, 'third_party'))
22from ply import lex
23
[email protected]683c8c52013-04-06 17:00:4624
25#
26# IDL Lexer
27#
28class IDLLexer(object):
[email protected]a8f94282013-08-14 01:42:3029 # 'literals' is a value expected by lex which specifies a list of valid
30 # literal tokens, meaning the token type and token value are identical.
31 literals = r'"*.(){}[],;:=+-/~|&^?<>'
32
33 # 't_ignore' contains ignored characters (spaces and tabs)
34 t_ignore = ' \t'
35
[email protected]683c8c52013-04-06 17:00:4636 # 'tokens' is a value required by lex which specifies the complete list
37 # of valid token types.
38 tokens = [
39 # Data types
40 'float',
41 'integer',
42 'string',
43
[email protected]683c8c52013-04-06 17:00:4644 # Symbol and keywords types
[email protected]683c8c52013-04-06 17:00:4645 'identifier',
46
[email protected]d4b86672013-04-11 16:28:3147 # MultiChar operators
48 'ELLIPSIS',
[email protected]683c8c52013-04-06 17:00:4649 ]
50
51 # 'keywords' is a map of string to token type. All tokens matching
52 # KEYWORD_OR_SYMBOL are matched against keywords dictionary, to determine
53 # if the token is actually a keyword.
54 keywords = {
55 'any' : 'ANY',
56 'attribute' : 'ATTRIBUTE',
57 'boolean' : 'BOOLEAN',
58 'byte' : 'BYTE',
[email protected]5885b692014-06-19 14:43:2459 'ByteString' : 'BYTESTRING',
[email protected]683c8c52013-04-06 17:00:4660 'callback' : 'CALLBACK',
61 'const' : 'CONST',
62 'creator' : 'CREATOR',
63 'Date' : 'DATE',
64 'deleter' : 'DELETER',
65 'dictionary' : 'DICTIONARY',
66 'DOMString' : 'DOMSTRING',
67 'double' : 'DOUBLE',
68 'enum' : 'ENUM',
jl9016ef322014-12-16 15:05:0969 'exception' : 'EXCEPTION',
[email protected]683c8c52013-04-06 17:00:4670 'false' : 'FALSE',
71 'float' : 'FLOAT',
bashicb5c16612015-08-19 02:11:2472 'FrozenArray' : 'FROZENARRAY',
[email protected]683c8c52013-04-06 17:00:4673 'getter': 'GETTER',
74 'implements' : 'IMPLEMENTS',
75 'Infinity' : 'INFINITY',
76 'inherit' : 'INHERIT',
77 'interface' : 'INTERFACE',
jl9016ef322014-12-16 15:05:0978 'iterable': 'ITERABLE',
[email protected]683c8c52013-04-06 17:00:4679 'legacycaller' : 'LEGACYCALLER',
[email protected]683c8c52013-04-06 17:00:4680 'long' : 'LONG',
jl9016ef322014-12-16 15:05:0981 'maplike': 'MAPLIKE',
[email protected]683c8c52013-04-06 17:00:4682 'Nan' : 'NAN',
83 'null' : 'NULL',
84 'object' : 'OBJECT',
85 'octet' : 'OCTET',
86 'optional' : 'OPTIONAL',
87 'or' : 'OR',
yhirano6ce2b8e2014-10-20 12:49:0988 'partial' : 'PARTIAL',
89 'Promise' : 'PROMISE',
[email protected]683c8c52013-04-06 17:00:4690 'readonly' : 'READONLY',
[email protected]5885b692014-06-19 14:43:2491 'RegExp' : 'REGEXP',
raphael.kubo.da.costa4bec0d72017-02-22 10:12:4492 'record' : 'RECORD',
jl9016ef322014-12-16 15:05:0993 'required' : 'REQUIRED',
[email protected]683c8c52013-04-06 17:00:4694 'sequence' : 'SEQUENCE',
[email protected]5885b692014-06-19 14:43:2495 'serializer' : 'SERIALIZER',
jl9016ef322014-12-16 15:05:0996 'setlike' : 'SETLIKE',
[email protected]683c8c52013-04-06 17:00:4697 'setter': 'SETTER',
98 'short' : 'SHORT',
99 'static' : 'STATIC',
100 'stringifier' : 'STRINGIFIER',
[email protected]683c8c52013-04-06 17:00:46101 'typedef' : 'TYPEDEF',
102 'true' : 'TRUE',
103 'unsigned' : 'UNSIGNED',
104 'unrestricted' : 'UNRESTRICTED',
raphael.kubo.da.costa4bec0d72017-02-22 10:12:44105 'USVString' : 'USVSTRING',
[email protected]683c8c52013-04-06 17:00:46106 'void' : 'VOID'
107 }
108
[email protected]683c8c52013-04-06 17:00:46109 # Token definitions
110 #
111 # Lex assumes any value or function in the form of 't_<TYPE>' represents a
112 # regular expression where a match will emit a token of type <TYPE>. In the
113 # case of a function, the function is called when a match is made. These
114 # definitions come from WebIDL.
[email protected]a8f94282013-08-14 01:42:30115 #
116 # These need to be methods for lexer construction, despite not using self.
117 # pylint: disable=R0201
[email protected]ac7b49d2013-04-12 18:48:47118 def t_ELLIPSIS(self, t):
119 r'\.\.\.'
120 return t
[email protected]683c8c52013-04-06 17:00:46121
[email protected]a8f94282013-08-14 01:42:30122 # Regex needs to be in the docstring
123 # pylint: disable=C0301
[email protected]ac7b49d2013-04-12 18:48:47124 def t_float(self, t):
125 r'-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)'
126 return t
[email protected]683c8c52013-04-06 17:00:46127
[email protected]ac7b49d2013-04-12 18:48:47128 def t_integer(self, t):
[email protected]9f1b57f2013-08-07 05:08:09129 r'-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)'
[email protected]ac7b49d2013-04-12 18:48:47130 return t
[email protected]d4b86672013-04-11 16:28:31131
[email protected]683c8c52013-04-06 17:00:46132
[email protected]683c8c52013-04-06 17:00:46133 # A line ending '\n', we use this to increment the line number
134 def t_LINE_END(self, t):
135 r'\n+'
136 self.AddLines(len(t.value))
137
138 # We do not process escapes in the IDL strings. Strings are exclusively
139 # used for attributes and enums, and not used as typical 'C' constants.
140 def t_string(self, t):
141 r'"[^"]*"'
142 t.value = t.value[1:-1]
143 self.AddLines(t.value.count('\n'))
144 return t
145
146 # A C or C++ style comment: /* xxx */ or //
Kenichi Ishibashi4e46f032017-06-23 07:26:05147 # This token is ignored.
[email protected]683c8c52013-04-06 17:00:46148 def t_COMMENT(self, t):
149 r'(/\*(.|\n)*?\*/)|(//.*(\n[ \t]*//.*)*)'
150 self.AddLines(t.value.count('\n'))
[email protected]683c8c52013-04-06 17:00:46151
[email protected]683c8c52013-04-06 17:00:46152 # A symbol or keyword.
153 def t_KEYWORD_OR_SYMBOL(self, t):
154 r'_?[A-Za-z][A-Za-z_0-9]*'
155
156 # All non-keywords are assumed to be symbols
157 t.type = self.keywords.get(t.value, 'identifier')
158
159 # We strip leading underscores so that you can specify symbols with the same
160 # value as a keywords (E.g. a dictionary named 'interface').
161 if t.value[0] == '_':
162 t.value = t.value[1:]
163 return t
164
165 def t_ANY_error(self, t):
166 msg = 'Unrecognized input'
[email protected]ac7b49d2013-04-12 18:48:47167 line = self.Lexer().lineno
[email protected]683c8c52013-04-06 17:00:46168
169 # If that line has not been accounted for, then we must have hit
170 # EoF, so compute the beginning of the line that caused the problem.
171 if line >= len(self.index):
172 # Find the offset in the line of the first word causing the issue
173 word = t.value.split()[0]
174 offs = self.lines[line - 1].find(word)
175 # Add the computed line's starting position
[email protected]ac7b49d2013-04-12 18:48:47176 self.index.append(self.Lexer().lexpos - offs)
[email protected]683c8c52013-04-06 17:00:46177 msg = 'Unexpected EoF reached after'
178
[email protected]ac7b49d2013-04-12 18:48:47179 pos = self.Lexer().lexpos - self.index[line]
[email protected]683c8c52013-04-06 17:00:46180 out = self.ErrorMessage(line, pos, msg)
181 sys.stderr.write(out + '\n')
[email protected]d4b86672013-04-11 16:28:31182 self._lex_errors += 1
[email protected]683c8c52013-04-06 17:00:46183
184
185 def AddLines(self, count):
186 # Set the lexer position for the beginning of the next line. In the case
187 # of multiple lines, tokens can not exist on any of the lines except the
188 # last one, so the recorded value for previous lines are unused. We still
189 # fill the array however, to make sure the line count is correct.
[email protected]ac7b49d2013-04-12 18:48:47190 self.Lexer().lineno += count
[email protected]683c8c52013-04-06 17:00:46191 for _ in range(count):
[email protected]ac7b49d2013-04-12 18:48:47192 self.index.append(self.Lexer().lexpos)
[email protected]683c8c52013-04-06 17:00:46193
194 def FileLineMsg(self, line, msg):
195 # Generate a message containing the file and line number of a token.
[email protected]ac7b49d2013-04-12 18:48:47196 filename = self.Lexer().filename
[email protected]683c8c52013-04-06 17:00:46197 if filename:
198 return "%s(%d) : %s" % (filename, line + 1, msg)
199 return "<BuiltIn> : %s" % msg
200
201 def SourceLine(self, line, pos):
202 # Create a source line marker
[email protected]d4b86672013-04-11 16:28:31203 caret = ' ' * pos + '^'
[email protected]683c8c52013-04-06 17:00:46204 # We decrement the line number since the array is 0 based while the
205 # line numbers are 1 based.
206 return "%s\n%s" % (self.lines[line - 1], caret)
207
208 def ErrorMessage(self, line, pos, msg):
209 return "\n%s\n%s" % (
210 self.FileLineMsg(line, msg),
211 self.SourceLine(line, pos))
212
[email protected]d4b86672013-04-11 16:28:31213#
214# Tokenizer
215#
216# The token function returns the next token provided by IDLLexer for matching
217# against the leaf paterns.
218#
219 def token(self):
[email protected]ac7b49d2013-04-12 18:48:47220 tok = self.Lexer().token()
[email protected]d4b86672013-04-11 16:28:31221 if tok:
222 self.last = tok
223 return tok
224
225
[email protected]683c8c52013-04-06 17:00:46226 def GetTokens(self):
227 outlist = []
228 while True:
[email protected]ac7b49d2013-04-12 18:48:47229 t = self.Lexer().token()
[email protected]683c8c52013-04-06 17:00:46230 if not t:
231 break
232 outlist.append(t)
233 return outlist
234
[email protected]d4b86672013-04-11 16:28:31235 def Tokenize(self, data, filename='__no_file__'):
[email protected]ac7b49d2013-04-12 18:48:47236 lexer = self.Lexer()
237 lexer.lineno = 1
238 lexer.filename = filename
239 lexer.input(data)
[email protected]d4b86672013-04-11 16:28:31240 self.lines = data.split('\n')
[email protected]683c8c52013-04-06 17:00:46241
[email protected]ac7b49d2013-04-12 18:48:47242 def KnownTokens(self):
243 return self.tokens
244
245 def Lexer(self):
246 if not self._lexobj:
247 self._lexobj = lex.lex(object=self, lextab=None, optimize=0)
248 return self._lexobj
249
[email protected]ac7b49d2013-04-12 18:48:47250 def _AddToken(self, token):
251 if token in self.tokens:
252 raise RuntimeError('Same token: ' + token)
253 self.tokens.append(token)
254
255 def _AddTokens(self, tokens):
256 for token in tokens:
257 self._AddToken(token)
258
259 def _AddKeywords(self, keywords):
260 for key in keywords:
261 value = key.upper()
262 self._AddToken(value)
263 self.keywords[key] = value
264
[email protected]a958ace2013-06-29 20:51:01265 def _DelKeywords(self, keywords):
266 for key in keywords:
267 self.tokens.remove(key.upper())
268 del self.keywords[key]
269
[email protected]d4b86672013-04-11 16:28:31270 def __init__(self):
271 self.index = [0]
272 self._lex_errors = 0
273 self.linex = []
274 self.filename = None
[email protected]ac7b49d2013-04-12 18:48:47275 self.keywords = {}
276 self.tokens = []
[email protected]ac7b49d2013-04-12 18:48:47277 self._AddTokens(IDLLexer.tokens)
278 self._AddKeywords(IDLLexer.keywords)
279 self._lexobj = None
[email protected]a8f94282013-08-14 01:42:30280 self.last = None
281 self.lines = None
[email protected]683c8c52013-04-06 17:00:46282
[email protected]ac7b49d2013-04-12 18:48:47283# If run by itself, attempt to build the lexer
284if __name__ == '__main__':
[email protected]a8f94282013-08-14 01:42:30285 lexer_object = IDLLexer()