• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# Copyright 2014 the V8 project 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
6# for py2/py3 compatibility
7from __future__ import print_function
8
9import json
10import optparse
11import os
12import random
13import shutil
14import subprocess
15import sys
16
17
18SKIPLIST = [
19  # Skip special d8 functions.
20  "load", "os", "print", "read", "readline", "quit"
21]
22
23
24def GetRandomObject():
25  return random.choice([
26    "0", "1", "2.5", "0x1000", "\"string\"", "{foo: \"bar\"}", "[1, 2, 3]",
27    "function() { return 0; }"
28  ])
29
30
31g_var_index = 0
32
33
34def GetVars(result, num, first = []):
35  global g_var_index
36  variables = []
37  for i in range(num):
38    variables.append("__v_%d" % g_var_index)
39    g_var_index += 1
40  for var in variables:
41    result.append("var %s = %s;" % (var, GetRandomObject()))
42  return ", ".join(first + variables)
43
44
45# Wraps |string| in try..catch.
46def TryCatch(result, string, exception_behavior = ""):
47  result.append("try { %s } catch(e) { %s }" % (string, exception_behavior))
48
49
50def BuildTests(function, full_name, options):
51  assert function["type"] == "function"
52  global g_var_index
53  g_var_index = 0
54  result = ["// AUTO-GENERATED BY tools/generate-builtins-tests.py.\n"]
55  result.append("// Function call test:")
56  length = function["length"]
57  TryCatch(result, "%s(%s);" % (full_name, GetVars(result, length)))
58
59  if "prototype" in function:
60    proto = function["prototype"]
61    result.append("\n// Constructor test:")
62    TryCatch(result,
63             "var recv = new %s(%s);" % (full_name, GetVars(result, length)),
64             "var recv = new Object();")
65
66    getters = []
67    methods = []
68    for prop in proto:
69      proto_property = proto[prop]
70      proto_property_type = proto_property["type"]
71      if proto_property_type == "getter":
72        getters.append(proto_property)
73        result.append("recv.__defineGetter__(\"%s\", "
74                      "function() { return %s; });" %
75                      (proto_property["name"], GetVars(result, 1)))
76      if proto_property_type == "number":
77        result.append("recv.__defineGetter__(\"%s\", "
78                      "function() { return %s; });" %
79                      (proto_property["name"], GetVars(result, 1)))
80      if proto_property_type == "function":
81        methods.append(proto_property)
82    if getters:
83      result.append("\n// Getter tests:")
84      for getter in getters:
85        result.append("print(recv.%s);" % getter["name"])
86    if methods:
87      result.append("\n// Method tests:")
88      for method in methods:
89        args = GetVars(result, method["length"], ["recv"])
90        call = "%s.prototype.%s.call(%s)" % (full_name, method["name"], args)
91        TryCatch(result, call)
92
93  filename = os.path.join(options.outdir, "%s.js" % (full_name))
94  with open(filename, "w") as f:
95    f.write("\n".join(result))
96    f.write("\n")
97
98
99def VisitObject(obj, path, options):
100  obj_type = obj["type"]
101  obj_name = "%s%s" % (path, obj["name"])
102  if obj_type == "function":
103    BuildTests(obj, obj_name, options)
104  if "properties" in obj:
105    for prop_name in obj["properties"]:
106      prop = obj["properties"][prop_name]
107      VisitObject(prop, "%s." % (obj_name), options)
108
109
110def ClearGeneratedFiles(options):
111  if os.path.exists(options.outdir):
112    shutil.rmtree(options.outdir)
113
114
115def GenerateTests(options):
116  ClearGeneratedFiles(options)  # Re-generate everything.
117  output = subprocess.check_output(
118      "%s %s" % (options.d8, options.script), shell=True).strip()
119  objects = json.loads(output)
120
121  os.makedirs(options.outdir)
122  for obj_name in objects:
123    if obj_name in SKIPLIST: continue
124    obj = objects[obj_name]
125    VisitObject(obj, "", options)
126
127
128def BuildOptions():
129  result = optparse.OptionParser()
130  result.add_option("--d8", help="d8 binary to use",
131                    default="out/ia32.release/d8")
132  result.add_option("--outdir", help="directory where to place generated tests",
133                    default="test/mjsunit/builtins-gen")
134  result.add_option("--script", help="builtins detector script to run in d8",
135                    default="tools/detect-builtins.js")
136  return result
137
138
139def Main():
140  parser = BuildOptions()
141  (options, args) = parser.parse_args()
142  if len(args) != 1 or args[0] == "help":
143    parser.print_help()
144    return 1
145  action = args[0]
146
147  if action == "generate":
148    GenerateTests(options)
149    return 0
150
151  if action == "clear":
152    ClearGeneratedFiles(options)
153    return 0
154
155  print("Unknown action: %s" % action)
156  parser.print_help()
157  return 1
158
159
160if __name__ == "__main__":
161  sys.exit(Main())
162