3 # Copyright 2006-2008 the V8 project authors. All rights reserved.
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
8 # * Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 # * Redistributions in binary form must reproduce the above
11 # copyright notice, this list of conditions and the following
12 # disclaimer in the documentation and/or other materials provided
13 # with the distribution.
14 # * Neither the name of Google Inc. nor the names of its
15 # contributors may be used to endorse or promote products derived
16 # from this software without specific prior written permission.
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 # This is a utility for converting JavaScript source code into C-style
31 # char arrays. It is used for embedded JavaScript code in the V8
35 from os.path import dirname
40 sys.path.append(dirname(__file__) + "/../deps/v8/tools");
44 def ToCArray(filename, lines):
50 if chr == "\n" or chr == "\r":
57 print 'non-ascii value ' + filename + ':' + str(row) + ':' + str(col)
60 result.append(str(value))
62 return ", ".join(result)
65 def CompressScript(lines, do_jsmin):
66 # If we're not expecting this code to be user visible, we can run it through
67 # a more aggressive minifier.
69 minifier = JavaScriptMinifier()
70 return minifier.JSMinify(lines)
72 # Remove stuff from the source that we don't want to appear when
73 # people print the source code using Function.prototype.toString().
74 # Note that we could easily compress the scripts mode but don't
75 # since we want it to remain readable.
76 #lines = re.sub('//.*\n', '\n', lines) # end-of-line comments
77 #lines = re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', lines) # comments.
78 #lines = re.sub('\s+\n+', '\n', lines) # trailing whitespace
82 def ReadFile(filename):
83 file = open(filename, "rt")
91 def ReadLines(filename):
93 for line in open(filename, "rt"):
95 line = line[:line.index('#')]
102 def LoadConfigFrom(name):
104 config = ConfigParser.ConfigParser()
109 def ParseValue(string):
110 string = string.strip()
111 if string.startswith('[') and string.endswith(']'):
112 return string.lstrip('[').rstrip(']').split()
117 def ExpandConstants(lines, constants):
118 for key, value in constants.items():
119 lines = lines.replace(key, str(value))
123 def ExpandMacros(lines, macros):
124 for name, macro in macros.items():
125 start = lines.find(name + '(', 0)
127 # Scan over the arguments
128 assert lines[start + len(name)] == '('
130 end = start + len(name) + 1
135 # Remember to expand recursively in the arguments
136 replacement = ExpandMacros(str.strip(), macros)
137 mapping[macro.args[arg_index]] = replacement
138 while end < len(lines) and height > 0:
139 # We don't count commas at higher nesting levels.
140 if lines[end] == ',' and height == 1:
141 add_arg(lines[last_match:end])
143 elif lines[end] in ['(', '{', '[']:
145 elif lines[end] in [')', '}', ']']:
148 # Remember to add the last match.
149 add_arg(lines[last_match:end-1])
150 result = macro.expand(mapping)
151 # Replace the occurrence of the macro with the expansion
152 lines = lines[:start] + result + lines[end:]
153 start = lines.find(name + '(', start)
158 def __init__(self, args, body):
161 def expand(self, mapping):
163 for key, value in mapping.items():
164 result = result.replace(key, value)
168 def __init__(self, args, fun):
171 def expand(self, mapping):
173 for arg in self.args:
174 args.append(mapping[arg])
175 return str(self.fun(*args))
177 CONST_PATTERN = re.compile('^const\s+([a-zA-Z0-9_]+)\s*=\s*([^;]*);$')
178 MACRO_PATTERN = re.compile('^macro\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*=\s*([^;]*);$')
179 PYTHON_MACRO_PATTERN = re.compile('^python\s+macro\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*=\s*([^;]*);$')
181 def ReadMacros(lines):
185 hash = line.find('#')
186 if hash != -1: line = line[:hash]
188 if len(line) is 0: continue
189 const_match = CONST_PATTERN.match(line)
191 name = const_match.group(1)
192 value = const_match.group(2).strip()
193 constants[name] = value
195 macro_match = MACRO_PATTERN.match(line)
197 name = macro_match.group(1)
198 args = map(string.strip, macro_match.group(2).split(','))
199 body = macro_match.group(3).strip()
200 macros[name] = TextMacro(args, body)
202 python_match = PYTHON_MACRO_PATTERN.match(line)
204 name = python_match.group(1)
205 args = map(string.strip, python_match.group(2).split(','))
206 body = python_match.group(3).strip()
207 fun = eval("lambda " + ",".join(args) + ': ' + body)
208 macros[name] = PythonMacro(args, fun)
210 raise Exception("Illegal line: " + line)
211 return (constants, macros)
214 HEADER_TEMPLATE = """\
215 #ifndef node_natives_h
216 #define node_natives_h
227 static const struct _native natives[] = {
231 { NULL, NULL, 0 } /* sentinel */
240 NATIVE_DECLARATION = """\
241 { "%(id)s", %(id)s_native, sizeof(%(id)s_native)-1 },
244 SOURCE_DECLARATION = """\
245 const char %(id)s_native[] = { %(data)s };
249 GET_DELAY_INDEX_CASE = """\
250 if (strcmp(name, "%(id)s") == 0) return %(i)i;
254 GET_DELAY_SCRIPT_SOURCE_CASE = """\
255 if (index == %(i)i) return Vector<const char>(%(id)s, %(length)i);
259 GET_DELAY_SCRIPT_NAME_CASE = """\
260 if (index == %(i)i) return Vector<const char>("%(name)s", %(length)i);
263 def JS2C(source, target):
267 # Locate the macros file name.
273 if (os.path.split(str(s))[1]).endswith('macros.py'):
274 macro_lines.extend(ReadLines(str(s)))
278 # Process input from all *macro.py files
279 (consts, macros) = ReadMacros(macro_lines)
281 # Build source code lines
283 source_lines_empty = []
288 delay = str(s).endswith('-delay.js')
289 lines = ReadFile(str(s))
290 do_jsmin = lines.find('// jsminify this file, js2c: jsmin') != -1
292 lines = ExpandConstants(lines, consts)
293 lines = ExpandMacros(lines, macros)
294 lines = CompressScript(lines, do_jsmin)
295 data = ToCArray(s, lines)
296 id = os.path.basename(str(s)).split('.')[0]
297 if delay: id = id[:-6]
299 delay_ids.append((id, len(lines)))
301 ids.append((id, len(lines)))
302 source_lines.append(SOURCE_DECLARATION % { 'id': id, 'data': data })
303 source_lines_empty.append(SOURCE_DECLARATION % { 'id': id, 'data': 0 })
304 native_lines.append(NATIVE_DECLARATION % { 'id': id })
306 # Build delay support functions
307 get_index_cases = [ ]
308 get_script_source_cases = [ ]
309 get_script_name_cases = [ ]
312 for (id, length) in delay_ids:
313 native_name = "native %s.js" % id
314 get_index_cases.append(GET_DELAY_INDEX_CASE % { 'id': id, 'i': i })
315 get_script_source_cases.append(GET_DELAY_SCRIPT_SOURCE_CASE % {
320 get_script_name_cases.append(GET_DELAY_SCRIPT_NAME_CASE % {
322 'length': len(native_name),
327 for (id, length) in ids:
328 native_name = "native %s.js" % id
329 get_index_cases.append(GET_DELAY_INDEX_CASE % { 'id': id, 'i': i })
330 get_script_source_cases.append(GET_DELAY_SCRIPT_SOURCE_CASE % {
335 get_script_name_cases.append(GET_DELAY_SCRIPT_NAME_CASE % {
337 'length': len(native_name),
343 output = open(str(target[0]), "w")
344 output.write(HEADER_TEMPLATE % {
345 'builtin_count': len(ids) + len(delay_ids),
346 'delay_count': len(delay_ids),
347 'source_lines': "\n".join(source_lines),
348 'native_lines': "\n".join(native_lines),
349 'get_index_cases': "".join(get_index_cases),
350 'get_script_source_cases': "".join(get_script_source_cases),
351 'get_script_name_cases': "".join(get_script_name_cases)
356 output = open(str(target[1]), "w")
357 output.write(HEADER_TEMPLATE % {
358 'builtin_count': len(ids) + len(delay_ids),
359 'delay_count': len(delay_ids),
360 'source_lines': "\n".join(source_lines_empty),
361 'get_index_cases': "".join(get_index_cases),
362 'get_script_source_cases': "".join(get_script_source_cases),
363 'get_script_name_cases': "".join(get_script_name_cases)
368 natives = sys.argv[1]
369 source_files = sys.argv[2:]
370 JS2C(source_files, [natives])
372 if __name__ == "__main__":