Skip to content

Commit

Permalink
Optimizations and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
mattbasta committed Sep 11, 2012
1 parent d838594 commit e8e61f5
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 130 deletions.
91 changes: 38 additions & 53 deletions validator/testcases/javascript/actions.py
Expand Up @@ -71,9 +71,8 @@ def trace_member(traverser, node, instantiate=False):
test_identifier(traverser, identifier)

traverser._debug("MEMBER_EXP>>PROPERTY: %s" % identifier)
output = base.get(traverser=traverser,
instantiate=instantiate,
name=identifier)
output = base.get(
traverser=traverser, instantiate=instantiate, name=identifier)
output.context = base.context
return output

Expand All @@ -83,23 +82,17 @@ def trace_member(traverser, node, instantiate=False):

# If we're supposed to instantiate the object and it doesn't already
# exist, instantitate the object.
if (instantiate and not (traverser._is_global(node["name"]) or
traverser._is_local_variable(node["name"]))):
if instantiate and not traverser._is_defined(node["name"]):
output = JSWrapper(JSObject(), traverser=traverser)
traverser.contexts[0].set(node["name"], output)
else:
output = traverser._seek_variable(node["name"])

output = _expand_globals(traverser, output)

return output
return _expand_globals(traverser, output)
else:
traverser._debug("MEMBER_EXP>>ROOT:EXPRESSION")
# It's an expression, so just try your damndest.
traversed = traverser._traverse_node(node)
if not isinstance(traversed, JSWrapper):
return JSWrapper(traversed, traverser=traverser)
return traversed
return traverser._traverse_node(node)


def test_identifier(traverser, name):
Expand Down Expand Up @@ -175,12 +168,9 @@ def wrap(traverser, node):


def _define_function(traverser, node):
"Makes a function happy"

me = _function(traverser, node)
traverser._peek_context(2).set(node["id"]["name"], me)

return True
return me


def _func_expr(traverser, node):
Expand Down Expand Up @@ -364,7 +354,6 @@ def _call_expression(traverser, node):
column=traverser.position,
context=traverser.context)


if (member.is_global and
"dangerous" in member.value and
isinstance(member.value["dangerous"], types.LambdaType)):
Expand All @@ -373,26 +362,26 @@ def _call_expression(traverser, node):
t = traverser._traverse_node
result = dangerous(a=args, t=t, e=traverser.err)
if result and "name" in member.value:
# Generate a string representation of the params
params = u", ".join([_get_as_str(t(p).get_literal_value()) for
p in args])
traverser.err.warning(("testcases_javascript_actions",
"_call_expression",
"called_dangerous_global"),
"'%(name)s' function called in potentially dangerous manner"
% member.value,
result if
isinstance(result, (types.StringTypes, list, tuple)) else
"The global %(name)s function was called using a set "
"of dangerous parameters. %(name)s calls of this nature "
"are deprecated." % member.value,
filename=traverser.filename,
line=traverser.line,
column=traverser.position,
context=traverser.context)

elif node["callee"]["type"] == "MemberExpression" and \
node["callee"]["property"]["type"] == "Identifier":
## Generate a string representation of the params
#params = u", ".join([_get_as_str(t(p).get_literal_value()) for
# p in args])
traverser.err.warning(
err_id=("testcases_javascript_actions", "_call_expression",
"called_dangerous_global"),
warning="`%s` called in potentially dangerous manner" %
member.value,
description=result if isinstance(result, (types.StringTypes,
list, tuple)) else
"The global `%s` function was called using a set "
"of dangerous parameters. `%s` calls of this "
"nature are deprecated." % member.value,
filename=traverser.filename,
line=traverser.line,
column=traverser.position,
context=traverser.context)

elif (node["callee"]["type"] == "MemberExpression" and
node["callee"]["property"]["type"] == "Identifier"):

# If we can identify the function being called on any member of any
# instance, we can use that to either generate an output value or test
Expand All @@ -406,7 +395,7 @@ def _call_expression(traverser, node):
if member.is_global and "return" in member.value:
return member.value["return"](wrapper=member, arguments=args,
traverser=traverser)
return JSWrapper(traverser=traverser)
return JSWrapper(JSObject(), dirty=True, traverser=traverser)


def _call_settimeout(a, t, e):
Expand Down Expand Up @@ -463,9 +452,9 @@ def _readonly_top(t, r, rn):
err_id=("testcases_javascript_actions",
"_readonly_top"),
notice="window.top is a reserved variable",
description="The 'top' global variable is reserved and cannot be "
description="The `top` global variable is reserved and cannot be "
"assigned any values starting with Gecko 6. Review your "
"code for any uses of the 'top' global, and refer to "
"code for any uses of the `top` global, and refer to "
"%s for more information." % BUGZILLA_BUG % 654137,
filename=t.filename,
line=t.line,
Expand All @@ -480,11 +469,11 @@ def _readonly_top(t, r, rn):


def _expression(traverser, node):
"Evaluates an expression and returns the result"
result = traverser._traverse_node(node["expression"])
if not isinstance(result, JSWrapper):
return JSWrapper(result, traverser=traverser)
return result
"""
This is a helper method that allows node definitions to point at
`_traverse_node` without needing a reference to a traverser.
"""
return traverser._traverse_node(node["expression"])


def _get_this(traverser, node):
Expand Down Expand Up @@ -526,11 +515,8 @@ def _ident(traverser, node):
# Ban bits like "newThread"
test_identifier(traverser, name)

if (traverser._is_local_variable(name) or
traverser._is_global(name)):
# This function very nicely wraps with JSWrapper for us :)
found = traverser._seek_variable(name)
return found
if traverser._is_defined(name):
return traverser._seek_variable(name)

return JSWrapper(JSObject(), traverser=traverser, dirty=True)

Expand Down Expand Up @@ -642,8 +628,8 @@ def _expr_assignment(traverser, node):
if lit_right is None:
lit_right = 0

if isinstance(lit_left, types.StringTypes) or \
isinstance(lit_right, types.StringTypes):
if (isinstance(lit_left, types.StringTypes) or
isinstance(lit_right, types.StringTypes)):
lit_left = _get_as_str(lit_left)
lit_right = _get_as_str(lit_right)

Expand Down Expand Up @@ -896,4 +882,3 @@ def _get_as_str(value):
except ValueError:
pass
return unicode(value)

6 changes: 3 additions & 3 deletions validator/testcases/javascript/call_definitions.py
Expand Up @@ -188,8 +188,8 @@ def definition(wrapper, arguments, traverser):

traverser._debug("(Building XPCOM...)")

inst = traverser._build_global(method,
copy.deepcopy(argz.value["xpcom_map"]()))
inst = traverser._build_global(
method, argz.value["xpcom_map"]())
inst.value["overwritable"] = True

if extend or mutate:
Expand All @@ -212,7 +212,7 @@ def definition(wrapper, arguments, traverser):
if extend and mutate:
if callable(parent.value["value"]):
parent.value["value"] = \
copy.deepcopy(parent.value["value"](t=traverser))
parent.value["value"](t=traverser)

parent.value["value"].update(inst.value["value"])
return parent
Expand Down
6 changes: 4 additions & 2 deletions validator/testcases/javascript/instanceactions.py
Expand Up @@ -214,8 +214,10 @@ def PageMod(args, traverser, node, wrapper):
return

content_script = pm_properties.get(traverser, "contentScript")
content_script = content_script.get_literal_value()
if not isinstance(content_script, (str, unicode)):
if not content_script.is_literal():
return
content_script = actions._get_as_str(content_script.get_literal_value())
if not content_script.strip():
return

import validator.testcases.scripting as sub_scripting
Expand Down
20 changes: 7 additions & 13 deletions validator/testcases/javascript/spidermonkey.py
Expand Up @@ -18,12 +18,8 @@ def get_tree(code, err=None, filename=None, shell=None):
if not code or not shell:
return None

# Filter characters, convert to Unicode, etc.
code = prepare_code(code, err, filename)

try:
tree = _get_tree(code, shell)
return tree
return _get_tree(code, shell)
except JSReflectException as exc:
str_exc = str(exc).strip("'\"")
if ("SyntaxError" in str_exc or
Expand Down Expand Up @@ -74,14 +70,13 @@ def line_num(self, line_num):
return self


def prepare_code(code, err, filename):
"Prepares code for tree generation"
# Acceptable unicode characters still need to be stripped. Just remove the
# slash: a character is necessary to prevent bad identifier errors
code = JS_ESCAPE.sub("u", code)
def prepare_code(code):
"""Prepare code for tree generation."""

code = unicodehelper.decode(code)
return code
# Acceptable unicode characters still need to be stripped. Just remove the
# slash: a character is necessary to prevent bad identifier errors.
return JS_ESCAPE.sub("u", code)


def _get_tree(code, shell):
Expand All @@ -90,10 +85,9 @@ def _get_tree(code, shell):
if not code:
return None

code = unicodehelper.decode(code)
code = prepare_code(code)

temp = tempfile.NamedTemporaryFile(mode="w+b", delete=False)
#temp.write(codecs.BOM_UTF8)
temp.write(code.encode("utf_8"))
temp.flush()

Expand Down

0 comments on commit e8e61f5

Please sign in to comment.