Commits

Waldemar Kornewald committed ce687f0

changed "self"->"this" translation, so it only happens when you're within a function that defines a "self" parameter. this can be important when combining PyvaScript with pyjs

Comments (0)

Files changed (3)

pyvascript/grammar.py

         'def', 'default', 'del', 'delete', 'do', 'elif', 'else', 'except',
         'false', 'finally', 'for', 'function', 'if', 'in', 'is', 'instanceof',
         'new', 'not', 'null', 'or', 'pass', 'raise', 'return', 'switch',
-        'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while',
-        'with', 'yield',))
+        'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with',
+        'yield',))
     hex_digits = '0123456789abcdef'
 
     def __init__(self, *args, **kwargs):
         self.var_stack = []
         self.temp_var_id = 0
 
+    def get_name(self, name):
+        if name == 'self' and name not in self.global_vars:
+            return name
+        return self.name_map.get(name, name)
+
     def make_temp_var(self, name, prefix='_$tmp'):
         self.temp_var_id += 1
         return '%s%s_%s' % (prefix, self.temp_var_id, name)
 
     def make_func(self, name, args, body):
         if name:
-            name = self.name_map.get(name[1], name[1])
+            name = self.get_name(name[1])
             self.register_var(name)
             func = '%s = function' % name
             body += ';'
         else:
             func = 'function'
-        if args and args[0] == self.name_map.get('self', 'self'):
+        if args and args[0] == self.get_name('self'):
             args = args[1:]
         return '%s(%s) %s' % (func, ', '.join(args), body)

pyvascript/translator.ometa

 binop    'not in' expr:x expr:y -> '!(%s in %s)' % (x, y)
 binop    :op expr:x expr:y -> '(%s %s %s)' % (x, self.binop_map.get(op, op), y)
 
-name      :n       -> self.name_map.get(n, n)
+name      :n       -> self.get_name(n)
 number    :n       -> str(n)
 hexnumber :n       -> hex(n)
 string    :s       -> "'%s'" % s.encode('string_escape')
           x = 5;
         })();
         """)
+
+    def test_self(self):
+        self.check("""
+        self.f()
+        """, """
+        self.f();
+        """)
+
+        self.check("""
+        def f():
+            self.f()
+        """, """
+        f = function() {
+          self.f();
+        };
+        """)
+
+        self.check("""
+        def f(self):
+            self.f()
+        """, """
+        f = function() {
+          this.f();
+        };
+        """)
+
+        self.check("""
+        def f(self):
+            myself = self
+            def g():
+                myself.f()
+        """, """
+        f = function() {
+          var g, myself;
+          myself = this;
+          g = function() {
+            myself.f();
+          };
+        };
+        """)