Skip to content

Commit

Permalink
Merge pull request #433 from jstepien/module-const-set
Browse files Browse the repository at this point in the history
Add Module#const_set
  • Loading branch information
alex committed Feb 23, 2013
2 parents 5e2bc34 + ec8f92f commit 9a8fb08
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
5 changes: 0 additions & 5 deletions spec/tags/core/module/const_set_tags.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1 @@
fails:Module#const_set sets the constant specified by a String or Symbol to the given value
fails:Module#const_set returns the value set
fails:Module#const_set sets the name of an anonymous module
fails:Module#const_set raises a NameError if the name contains non-alphabetic characters except '_'
fails:Module#const_set calls #to_str to convert the given name to a String
fails:Module#const_set raises a TypeError if conversion to a String by calling #to_str fails
9 changes: 9 additions & 0 deletions tests/objects/test_moduleobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,15 @@ class A
end
""")

def test_const_set(self, space):
w_res = space.execute("""
m = Module.new
m.const_set 'ZzŻżŹź', :utf_8_is_legal
last_const = m.constants.last
return [last_const, m.const_get(last_const)]
""")
assert self.unwrap(space, w_res) == ['ZzŻżŹź', 'utf_8_is_legal']


class TestMethodVisibility(object):
def test_private(self, space):
Expand Down
5 changes: 5 additions & 0 deletions topaz/objects/moduleobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,11 @@ def method_const_get(self, space, const, inherit=True):
)
return w_res

@classdef.method("const_set", const="symbol")
def method_const_set(self, space, const, w_value):
space.set_const(self, const, w_value)
return w_value

@classdef.method("class_variable_defined?", name="symbol")
def method_class_variable_definedp(self, space, name):
return space.newbool(self.find_class_var(space, name) is not None)
Expand Down
12 changes: 12 additions & 0 deletions topaz/objspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,19 @@ def find_const(self, w_module, name):
w_res = self.send(w_module, self.newsymbol("const_missing"), [self.newsymbol(name)])
return w_res

@jit.elidable
def _is_legal_const_name(self, name):
for i in range(1, len(name)):
char = name[i]
if not (char.isalnum() or char == '_' or ord(char) > 127):
return False
return name[0].isupper()

def set_const(self, module, name, w_value):
if not self._is_legal_const_name(name):
raise self.error(self.w_NameError,
"wrong constant name %s" % name
)
module.set_const(self, name, w_value)

@jit.unroll_safe
Expand Down

0 comments on commit 9a8fb08

Please sign in to comment.