Merge remote-tracking branch 'ry/v0.8'
[platform/upstream/nodejs.git] / tools / js2c.py
1 #!/usr/bin/env python
2 #
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
6 # met:
7 #
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.
17 #
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.
29
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
32 # library.
33
34 import os
35 from os.path import dirname
36 import re
37 import sys
38 import string
39
40 sys.path.append(dirname(__file__) + "/../deps/v8/tools");
41 import jsmin
42
43
44 def ToCArray(filename, lines):
45   result = []
46   row = 1
47   col = 0
48   for chr in lines:
49     col += 1
50     if chr == "\n" or chr == "\r":
51       row += 1
52       col = 0
53
54     value = ord(chr)
55
56     if value >= 128:
57       print 'non-ascii value ' + filename + ':' + str(row) + ':' + str(col)
58       sys.exit(1);
59
60     result.append(str(value))
61   result.append("0")
62   return ", ".join(result)
63
64
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.
68   if do_jsmin:
69     minifier = JavaScriptMinifier()
70     return minifier.JSMinify(lines)
71
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
79   return lines
80
81
82 def ReadFile(filename):
83   file = open(filename, "rt")
84   try:
85     lines = file.read()
86   finally:
87     file.close()
88   return lines
89
90
91 def ReadLines(filename):
92   result = []
93   for line in open(filename, "rt"):
94     if '#' in line:
95       line = line[:line.index('#')]
96     line = line.strip()
97     if len(line) > 0:
98       result.append(line)
99   return result
100
101
102 def LoadConfigFrom(name):
103   import ConfigParser
104   config = ConfigParser.ConfigParser()
105   config.read(name)
106   return config
107
108
109 def ParseValue(string):
110   string = string.strip()
111   if string.startswith('[') and string.endswith(']'):
112     return string.lstrip('[').rstrip(']').split()
113   else:
114     return string
115
116
117 def ExpandConstants(lines, constants):
118   for key, value in constants.items():
119     lines = lines.replace(key, str(value))
120   return lines
121
122
123 def ExpandMacros(lines, macros):
124   for name, macro in macros.items():
125     start = lines.find(name + '(', 0)
126     while start != -1:
127       # Scan over the arguments
128       assert lines[start + len(name)] == '('
129       height = 1
130       end = start + len(name) + 1
131       last_match = end
132       arg_index = 0
133       mapping = { }
134       def add_arg(str):
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])
142           last_match = end + 1
143         elif lines[end] in ['(', '{', '[']:
144           height = height + 1
145         elif lines[end] in [')', '}', ']']:
146           height = height - 1
147         end = end + 1
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 + '(', end)
154   return lines
155
156 class TextMacro:
157   def __init__(self, args, body):
158     self.args = args
159     self.body = body
160   def expand(self, mapping):
161     result = self.body
162     for key, value in mapping.items():
163         result = result.replace(key, value)
164     return result
165
166 class PythonMacro:
167   def __init__(self, args, fun):
168     self.args = args
169     self.fun = fun
170   def expand(self, mapping):
171     args = []
172     for arg in self.args:
173       args.append(mapping[arg])
174     return str(self.fun(*args))
175
176 CONST_PATTERN = re.compile('^const\s+([a-zA-Z0-9_]+)\s*=\s*([^;]*);$')
177 MACRO_PATTERN = re.compile('^macro\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*=\s*([^;]*);$')
178 PYTHON_MACRO_PATTERN = re.compile('^python\s+macro\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*=\s*([^;]*);$')
179
180 def ReadMacros(lines):
181   constants = { }
182   macros = { }
183   for line in lines:
184     hash = line.find('#')
185     if hash != -1: line = line[:hash]
186     line = line.strip()
187     if len(line) is 0: continue
188     const_match = CONST_PATTERN.match(line)
189     if const_match:
190       name = const_match.group(1)
191       value = const_match.group(2).strip()
192       constants[name] = value
193     else:
194       macro_match = MACRO_PATTERN.match(line)
195       if macro_match:
196         name = macro_match.group(1)
197         args = map(string.strip, macro_match.group(2).split(','))
198         body = macro_match.group(3).strip()
199         macros[name] = TextMacro(args, body)
200       else:
201         python_match = PYTHON_MACRO_PATTERN.match(line)
202         if python_match:
203           name = python_match.group(1)
204           args = map(string.strip, python_match.group(2).split(','))
205           body = python_match.group(3).strip()
206           fun = eval("lambda " + ",".join(args) + ': ' + body)
207           macros[name] = PythonMacro(args, fun)
208         else:
209           raise Exception("Illegal line: " + line)
210   return (constants, macros)
211
212
213 HEADER_TEMPLATE = """\
214 #ifndef node_natives_h
215 #define node_natives_h
216 namespace node {
217
218 %(source_lines)s\
219
220 struct _native {
221   const char* name;
222   const char* source;
223   size_t source_len;
224 };
225
226 static const struct _native natives[] = {
227
228 %(native_lines)s\
229
230   { NULL, NULL, 0 } /* sentinel */
231
232 };
233
234 }
235 #endif
236 """
237
238
239 NATIVE_DECLARATION = """\
240   { "%(id)s", %(id)s_native, sizeof(%(id)s_native)-1 },
241 """
242
243 SOURCE_DECLARATION = """\
244   const char %(id)s_native[] = { %(data)s };
245 """
246
247
248 GET_DELAY_INDEX_CASE = """\
249     if (strcmp(name, "%(id)s") == 0) return %(i)i;
250 """
251
252
253 GET_DELAY_SCRIPT_SOURCE_CASE = """\
254     if (index == %(i)i) return Vector<const char>(%(id)s, %(length)i);
255 """
256
257
258 GET_DELAY_SCRIPT_NAME_CASE = """\
259     if (index == %(i)i) return Vector<const char>("%(name)s", %(length)i);
260 """
261
262 def JS2C(source, target):
263   ids = []
264   delay_ids = []
265   modules = []
266   # Locate the macros file name.
267   consts = {}
268   macros = {}
269   macro_lines = []
270
271   for s in source:
272     if (os.path.split(str(s))[1]).endswith('macros.py'):
273       macro_lines.extend(ReadLines(str(s)))
274     else:
275       modules.append(s)
276
277   # Process input from all *macro.py files
278   (consts, macros) = ReadMacros(macro_lines)
279
280   # Build source code lines
281   source_lines = [ ]
282   source_lines_empty = []
283
284   native_lines = []
285
286   for s in modules:
287     delay = str(s).endswith('-delay.js')
288     lines = ReadFile(str(s))
289     do_jsmin = lines.find('// jsminify this file, js2c: jsmin') != -1
290
291     lines = ExpandConstants(lines, consts)
292     lines = ExpandMacros(lines, macros)
293     lines = CompressScript(lines, do_jsmin)
294     data = ToCArray(s, lines)
295     id = os.path.basename(str(s)).split('.')[0]
296     if delay: id = id[:-6]
297     if delay:
298       delay_ids.append((id, len(lines)))
299     else:
300       ids.append((id, len(lines)))
301     source_lines.append(SOURCE_DECLARATION % { 'id': id, 'data': data })
302     source_lines_empty.append(SOURCE_DECLARATION % { 'id': id, 'data': 0 })
303     native_lines.append(NATIVE_DECLARATION % { 'id': id })
304   
305   # Build delay support functions
306   get_index_cases = [ ]
307   get_script_source_cases = [ ]
308   get_script_name_cases = [ ]
309
310   i = 0
311   for (id, length) in delay_ids:
312     native_name = "native %s.js" % id
313     get_index_cases.append(GET_DELAY_INDEX_CASE % { 'id': id, 'i': i })
314     get_script_source_cases.append(GET_DELAY_SCRIPT_SOURCE_CASE % {
315       'id': id,
316       'length': length,
317       'i': i
318     })
319     get_script_name_cases.append(GET_DELAY_SCRIPT_NAME_CASE % {
320       'name': native_name,
321       'length': len(native_name),
322       'i': i
323     });
324     i = i + 1
325
326   for (id, length) in ids:
327     native_name = "native %s.js" % id
328     get_index_cases.append(GET_DELAY_INDEX_CASE % { 'id': id, 'i': i })
329     get_script_source_cases.append(GET_DELAY_SCRIPT_SOURCE_CASE % {
330       'id': id,
331       'length': length,
332       'i': i
333     })
334     get_script_name_cases.append(GET_DELAY_SCRIPT_NAME_CASE % {
335       'name': native_name,
336       'length': len(native_name),
337       'i': i
338     });
339     i = i + 1
340
341   # Emit result
342   output = open(str(target[0]), "w")
343   output.write(HEADER_TEMPLATE % {
344     'builtin_count': len(ids) + len(delay_ids),
345     'delay_count': len(delay_ids),
346     'source_lines': "\n".join(source_lines),
347     'native_lines': "\n".join(native_lines),
348     'get_index_cases': "".join(get_index_cases),
349     'get_script_source_cases': "".join(get_script_source_cases),
350     'get_script_name_cases': "".join(get_script_name_cases)
351   })
352   output.close()
353
354   if len(target) > 1:
355     output = open(str(target[1]), "w")
356     output.write(HEADER_TEMPLATE % {
357       'builtin_count': len(ids) + len(delay_ids),
358       'delay_count': len(delay_ids),
359       'source_lines': "\n".join(source_lines_empty),
360       'get_index_cases': "".join(get_index_cases),
361       'get_script_source_cases': "".join(get_script_source_cases),
362       'get_script_name_cases': "".join(get_script_name_cases)
363     })
364     output.close()
365
366 def main():
367   natives = sys.argv[1]
368   source_files = sys.argv[2:]
369   JS2C(source_files, [natives])
370
371 if __name__ == "__main__":
372   main()