GithubHelp home page GithubHelp logo

kovidgoyal / rapydscript-ng Goto Github PK

View Code? Open in Web Editor NEW
188.0 188.0 45.0 4.35 MB

A transpiler for a Python like language to JavaScript

License: BSD 2-Clause "Simplified" License

JavaScript 99.24% Shell 0.01% Python 0.18% HTML 0.30% CSS 0.26% Vim Script 0.01%
javascript python rapydscript-ng transpiler

rapydscript-ng's Introduction

Hi there 👋

Kovid's GitHub stats

Top Langs

GitHub Streak

The best way to contact me is to use my email address which is present at the top of most calibre or kitty source code files.

rapydscript-ng's People

Contributors

atsepkov avatar charleslaw avatar eevleevs avatar flying-sheep avatar icarito avatar kovidgoyal avatar prayagverma avatar wolfv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rapydscript-ng's Issues

Buidling in-browser compiler

I just updated rapydscript-ng, and I picked up the in-browser compiler from
https://kovidgoyal.github.io/rapydscript/repl/rapydscript.js

Just for completeness I also tried building it on Windows from "node bin/web-repl-export" but got this error:

M:\HP_Cdrive\workspace>cd rapydscript-ng

M:\HP_Cdrive\workspace\rapydscript-ng>node bin/web-repl-export
M:\HP_Cdrive\workspace\rapydscript-ng\bin\web-repl-export:83
process.chdir(base_dir);
^

Error: ENOENT: no such file or directory, uv_chdir
at Error (native)
at Object. (M:\HP_Cdrive\workspace\rapydscript-ng\bin\web-repl-export:83:9)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3

global and nonlocal

The documentation advocates the use of nonlocal rather than global, with reference to Python 3, with the comment "There is also global". However, it looks like a bug that RS 1) has not implemented "global" and 2) has not restricted "nonlocal" to use in nested methods, as seems to be the case in Python 3. At the time of implementing the use of RS in GlowScript, I was unfamiliar with "nonlocal" and in a preprocessing stage simply converted a user program "global" to "nonlocal", which did what was expected, except that in true Python one need not separately declare the variable in global scope, whereas in RS one must do so. Am I confused, or is this a bug?

Duplication in in-browser compiler

By accident I discovered that the minimized runtime code in the in-browser compiler (https://kovidgoyal.github.io/rapydscript/repl/rapydscript.js) has a large duplication. Code starting at

var RS_len;\nfunction RS_bool(val)

is duplicated after

baselib-plain-pretty.js":".

I of course don't know whether this is deliberate; it just seemed strange. I don't find this duplication if I build a runtime file (which I guess isn't needed, since it's all apparently present in the in-browser compiler).

Updated GlowScript to RS-NG

I made the following announcement to the GlowScript user forum. Thanks very much, Kovid, for the software itself and for the help you gave me in moving from RS to RS-NG.

The new GlowScript version 2.3 is a major update. It replaces the original RapydScript Python-to-JavaScript compiler with a newer version, RapydScript-NG by Kovid Goyal. This new version comes closer to handling true Python syntax but continues to offer high execution speed. It also provides most of the standard Python string methods: capitalize, strip, lstrip, rstrip, islower, isupper, isspace, lower, upper, swapcase, center, count, endswith, startswith, find, rfind, index, rindex, format, join, ljust, rjust, partition, rpartition, replace, split, rsplit, splitlines, and zfill.

Class returning as undefined

I prepared this simple test file in ClassA.py:

from __python__ import bound_methods
class A:
    def __init__(self,x):
        self.x = x
    def get(self):
        return self.x
b = A(5)
console.log(b)
c = b.get()
console.log(c)

I transpiled it with "rapydscript --bare --output ClassA.js ClassA.py"

I tested it as a library with this code:

test = A(23)
console.log(test)
t = test.get()

The output was

A {x: 5, ?s_object_id: 1}
5
undefined

followed by the error message TypeError: Cannot read property 'get' of undefined.

What am I doing wrong?

.hasOwnProperty missing on {}

I am a bit confused between objects, hash literals in javascript and dict literals in python.

I have merge method that worked in 0.4.9, but is failing in 0.7.1.

https://github.com/amitu/vyom/blob/master/vyom/events.pyj#L7-L15

Seems .hasOwnProperty is not always available. I fixed it by first checking if .hasOwnProperty is available on both, but some other piece of code is now not working, which too makes an assumption that .hasOwnProperty exists.

Can you clarify? I do not want python emulation, I was thinking {} in rs-ng is exactly same as {} in javascript, but it seems I need more clarifications.

False == 0 fails

Recipe:
Consider the following seemingly-innocent program:

a = 3==4
print("yyyyy", a, 0, a==0)

Desired and expected output:
yyyyy False 0 True

This works as expected under real python from the command line.
The corresponding javascript also works as expected. However...

Observed rapydscript behavior:
yyyyy false 0 false

This is 100% reproducible chez moi. I am using the latest rapydscript-ng, from a fresh git-pull. FWIW the old non-ng version exhibits the same misbehavior.

This is more important than it might seem. The example above is highly simplified, to facilitate debugging. The same issue affects more-complicated code in ways that are much harder to understand. This wastes significant amounts of programmer time.

This started out as BruceSherwood/glowscript#60 but is hereby pushed upstream.

Redirecting errors

Hy Kovid,

Is there a way to capture error messages when compiling, in order to display them on Javascript side ?

Regards

Class problem

I've encountered something that either shows that I'm still missing some piece of understanding, or there's a bug. I've tried to boil it down to a simple case.

Here is a simple test library which is transpiled using "rapydscript --bare":

from __python__ import bound_methods
class A:
    def __init__(self, x, y, **args):
        self.x = x
        self.y = y
        self.args = []
        for a in args:
            GSprint(a, args[a])
            self.args.append([a,args[a]])
    def get(self):
        ret = [self.x, self.y]
        for a in self.args:
            ret.append(a[0])
            ret.append(a[1])
        return ret

b = A(3, 7, canine='dog', feline='cat', states=50)
GSprint(b.get())

Here is a JavaScript program that uses the library:

var test = new A(50, 60, {canine:'coyote', feline:'jaguar', states:23})
console.log('Return:', test.get())

The output from execution shows that inside the library b = A(...) works properly, but test = new A(...) in the program that uses the library does not work properly:

3 7 Symbol(kwargs-object)
true Object {canine: "dog", feline: "cat", states: 50, Symbol(kwargs-object): true}
canine dog
feline cat
states 50
[3, 7, "canine", "dog", "feline", "cat", "states", 50]
50 60 Symbol(kwargs-object)
undefined Object {canine: "coyote", feline: "jaguar", states: 23}
Return: [50, 60]

The library contains this statement:

if (ρσ_kwargs_obj === null || typeof ρσ_kwargs_obj !== "object" || ρσ_kwargs_obj [ρσ_kwargs_symbol] !== true) ρσ_kwargs_obj = {};

If I remove the test for ρσ_kwargs_obj [ρσ_kwargs_symbol] !== true, like this,

if (ρσ_kwargs_obj === null || typeof ρσ_kwargs_obj !== "object") ρσ_kwargs_obj = {};

both instances of the class work properly:

3 7 Symbol(kwargs-object)
true Object {canine: "dog", feline: "cat", states: 50, Symbol(kwargs-object): true}
canine dog
feline cat
states 50
[3, 7, "canine", "dog", "feline", "cat", "states", 50]
50 60 Symbol(kwargs-object)
undefined Object {canine: "coyote", feline: "jaguar", states: 23}
canine coyote
feline jaguar
states 23
Return: [50, 60, "canine", "coyote", "feline", "jaguar", "states", 23]

In my actual application things work only if I make the change in the test, and the deletion doesn't seem to have any bad consequences. What is the function of that test?

Not an issue a suggestion...

Kovid,

Would it be possible, for the compiler to accept a string as an input ?
Indeed I would like to create a webservice so that i send the user code via ajax or websocket and pass the string directly to the compiler and get the output on stdout ?

A typo, and a question about separating browser compiler and run-time

Minor typo: In the reference to the work of Brian Turek, http://caligatio.github.com/jsSHA/ should be http://caligatio.github.io/jsSHA/

Kovid, I'm in the process of converting glowscript.org from rapydscript to rapydscript-ng. I had a useful exchange with Alex in which he and I agreed that my needs align better with your goals than with his. He wants to build an optimal tool for web programmers, with an appropriate mix of Python and JavaScript. I perceive that your goals are more along the lines of approximating true Python, without major sacrifices in run-time speed. The importance for VPython is that Ruth Chabay and I have been working hard to make the syntax of GlowScript VPython and Jupyter VPython be exactly the same, and it is the case that as long as outside libraries are not needed the same VPython program will run in both, very different, environments. Moreover, much of the use of VPython is in academic settings where Classic Python is used, both in STEM courses and in scientific work, so the closer the approximation the better.

My question: It's very helpful that you provide a ready-to-use in-browser compiler. I would like to separate the in-browser compiler from the run-time libraries, so that once the user program has been compiled it needs a smaller library in order to run. Can you explain what I need to do to create these two files?

The number of users registered at glowscript.org continues to rise dramatically, thanks to RapydScript:

http://www.glowscript.org/#/user/Bruce_Sherwood/folder/My_Programs/program/Users

Errors with equality

Kovid

I am testing the following code with my service:

def f():
for i in range(3):
yield i

x = [0, 1, 2]
y = [x for x in f()]

print("x : " , x)
print("y : " , y)

print( x == y)

Here is the result 👍

x : [0, 1, 2]
y : [0, 1, 2]
False

Meteor or Volt like in Python

Hi, first of all let me say you that your work is awesome.

I was thinking, just thinking, in something like Meteor or Ruby Volt in Python. Do you know them? It has to be with reactive programming.

I think rapydscript-ng is perfect for that but there's the need of a template language to compile to javascript that manage de DOM (and subscribe to reactive source data to redisplay the data when it changes). Do you know if rapydML is a good starting point for that?

I hope I've explained correctly the problem. In other case please let me know. Thanks :)

static member variables referenced inconsistantly

Static variables don't quite work properly, unless they are a function.

This works:

class Foo:
    value = def(): return 1
print(Foo.value())
[...]
Foo.prototype.value = function () {
    return 1;
};
print(Foo.prototype.value.call());

While a non-function does not:

class Foo:
    value = 1
print(Foo.value)
[...]
Foo.prototype.value = 1;
print(Foo.value);

"do and while" example doesn't translate

The following example from the README doesn't actually work:

a = 0
do and while a < 1:
    print(a)
    a += 1
test.pyj:test.pyj:Unexpected token: operator «&&» (line: 2, col: 3, pos: 9)

Likewise, from the README:

def(one, two) and call(this, 1, 2):
    pass
test.pyj:test.pyj:Unexpected token operator «&&», expected punc «:» (line: 1, col: 14, pos: 14)

I have no preference regarding fixing the README or actually making it work.

Starting issues

This may not be a real issue, or maybe at most a documentation issue, but I what I get attempting to compile my own code on my machine (Debian Linux) does not match the examples in the documentation nor what the REPL on this site gives me and (more importantly) doesn't work. It appears that what I get includes an enormous library of additional material and that somewhere in there something is causing a problem. When I strip this out the code works.

I don't know if this is a problem within the standard library or a user error in which I am compiling something wrong. I am currently compiling my code by issuing the command "rapydscript -o " in a terminal. I do notice that several of the symbols in the library code do not get displayed correctly when I view the source in the browser but I doubt that this is enough to break the code.

Building a library

In the README is a discussion about issues in calling routines in external libraries. I need to go the other way, to produce from Python code a JavaScript library. I successfully executed "npm install rapydscript-ng" and "npm install" and successfully ran "rapydscript" which produced what looks like correct JavaScript output, but when I try to reference a function named "PhysGraph" in the library (which is a class in the original Python file) I get an error message "PhysGraph is not defined", despite the fact that there is a "function PhysGraph" in the JavaScript. Do you have any suggestions about what I've done wrong? Thanks. (Incidentally, when I initially ran the Python code through the REPL, the output was entirely different and, in particular, didn't include any of the RS run-time functions. I guess the REPL is just used for seeing how code fragments compile?)

The 'new' keyword isn't always put in front of class instantiation

Here's an example program that illustrates the problem:

def oh_no():
    robot = Robot()

class Robot:
    pass

In the generated JavaScript, this is what oh_no() looks like:

function oh_no() {
    var robot;
    robot = Robot();
};

If the oh_no() function is put after the class definition, it does work. However, this behavior is not intuitive for people used to Python.

Import not working for sub-sub modules

Imports for deeper-than-two levels are not working correctly since the str.replace function (used with a string literal) only replaces the first occurrence.

Following code produces a ImportError even tho all neccessary folders contain a __init__.pyj:
import _import_two.sub2.subsub, _import_two.sub2.subsub as ts2
eq('subsub', _import_two.sub2.subsub.subsub_var)
eq('subsub', ts2.subsub_var)
eq('subsub', _import_two.sub2.subsub.subsub_func())

An easy fix is to change line 708 in parse.pyj to modpath = key.replace(/\./g, '/'), which will work correctly.
The import testcases don't catch this since only single-level submodule import is checked.

See:
https://github.com/kovidgoyal/rapydscript-ng/blob/master/src/parse.pyj#L708
and
http://www.w3schools.com/jsref/jsref_replace.asp

How/where to publish RapydScript packages?

If I make a RapydScript library, what is the best way to publish it? I know of npm, but it seems like it's mostly for JavaScript packages. Maybe PyPI? But if I use pip to install a package, is there a good way to make it visible to the RapydScript compiler?

static methods with parameters broken

class Foo:
    @staticmethod
    def bar(v):
        return v + 1

Generates:

[...]
Foo.bar = function bar(v) {
    return v + 1;
};
Object.defineProperties(Foo.prototype.bar, {
    __argnames__ : {value: ["v"]}
});

Where Foo.prototype.bar is an invalid name.

dict function?

The dict function, as in dict(a=5, b=3), gives an error when using the in-browser compiler. Am I failing to invoke some RS library?

missing semicolons in output --> nothing working at the momeht

Context

Consider the following trivial program:

bin/rapydscript --bare /dev/null | nodejs

Desired and Expected Behavior (normal python)

This works just fine under regular RapydScript

Observed Behavior (-ng fork)

bin/rapydscript --version
rapydscript-ng 0.4.0
bin/rapydscript --bare /dev/null | nodejs
[stdin]:1
self.stack=(new Error).stack};ValueError.prototype.name="ValueError"function _
                                                                    ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:73:16)
    at Object.<anonymous> ([stdin]-wrapper:6:22)
    at Module._compile (module.js:460:26)
    at evalScript (node.js:431:25)
    at Socket.<anonymous> (node.js:164:11)
    at Socket.emit (events.js:129:20)
    at _stream_readable.js:908:16
    at process._tickCallback (node.js:355:11)

Note: The same failure is observed with any program whatsoever AFAICT, independent of length. Hacking a semicolon into the output in the obvious place just reveals more problems of the same ilk.

Success! And a question

Thanks to your help (and work) I've been able to use rapydscript-ng in a test version of glowscript.org, even without updating the acorn and streamline libraries that permit operator overloading and synchronous code. I had to replace all instances of ρσ with RS because the streamline library considered ρσ to be an error, and perhaps updating streamline will eliminate that problem.

I think it is the case that I'm using acorn and streamline libraries that expect ES5, and I thought you said that you generate ES6, so I'm puzzled that this all works. I'm not knowledgeable in ES6, but looking at your generated code I don't see non-ES5 elements. Maybe I'm accidentally using Python code that doesn't happen to invoke ES6. Can you give an example of Python code that generates ES6? Thanks.

import a normal module

How do I import a normal Python module that is installed in the site-packages folder of a virtualenv?

ES5 Embedded Compiler?

Hi @kovidgoyal I want to create an app using cordova + embedded rs-ng, but many of todays devices doesnt support ES6 natively yet. How to create embedded compiler that support ES5 ?
Thx

String methods

I'm excited to be able to invoke Python string and dict methods. I notice that there are quite a few string methods not yet implemented, and this is something I could perhaps contribute to if it's not on your own to-do list. I noticed one bug: in my tests both islower and isupper give true for either 'a' or 'A'.

Bug using map() with functions with default keyword arguments?

Hi there,

I'm using RapydScript 0.7.3 and just discovered that my functions with default keyword arguments don't work with JavaScript's map() function.
Here's a code snippet to illustrate the problem.


Welcome to the RapydScript REPL! Press Ctrl+C then Ctrl+D to quit.
Use show_js=False to stop the REPL from showing the compiled JavaScript.

>>> def f(x):
...     return str(x)
...     
...     
---------- Compiled JavaScript ---------
function f(x) {
    return str(x);
};
Object.defineProperties(f, {
    __argnames__ : {value: ["x"]}
});

---------- Running JavaScript ---------
[Function: f]
>>> def g(x, flag=True):
...     if flag:
...         x = str(x)
...     return x
...     
...     
---------- Compiled JavaScript ---------
function g() {
    var x = ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [ρσ_kwargs_symbol] === true) ? undefined : arguments[0];
    var flag = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [ρσ_kwargs_symbol] === true)) ? g.__defaults__.flag : arguments[1];
    var ρσ_kwargs_obj = arguments[arguments.length-1];
    if (ρσ_kwargs_obj === null || typeof ρσ_kwargs_obj !== "object" || ρσ_kwargs_obj [ρσ_kwargs_symbol] !== true) ρσ_kwargs_obj = {};
    if (Object.prototype.hasOwnProperty.call(ρσ_kwargs_obj, "flag")){
        flag = ρσ_kwargs_obj.flag;
    }
    if (flag) {
        x = str(x);
    }
    return x;
};
Object.defineProperties(g, {
    __defaults__ : {value: {flag:true}},
    __handles_kwarg_interpolation__ : {value: true},
    __argnames__ : {value: ["x", "flag"]}
});

---------- Running JavaScript ---------
[Function: g]
>>> a = [1, 2]
---------- Compiled JavaScript ---------
var a;
a = ρσ_list_decorate([ 1, 2 ]);
---------- Running JavaScript ---------
[1, 2]
>>> a.map(f)
---------- Compiled JavaScript ---------
a.map(f);
---------- Running JavaScript ---------
[ '1', '2' ]
>>> a.map(g)  # Should be the same as a.map(f)
---------- Compiled JavaScript ---------
a.map(g);
---------- Running JavaScript ---------
[ 1, '2' ]

5e-2 does not compile

Thanks for pointing me to the information on how to embed the compiler, which worked instantly with some rather complex existing programs. There is a bug in compiling exponential-format numbers. If the exponent is negative, as in 5e-2 or 5E-2, there is a compile error (positive exponents are handled correctly):

Failed to compile RapydScript with error:
Invalid syntax: 5E
☛ a = 5E-2
☛ ⬆

And a quick question: Is something like stdlib already included in the embedded compiler, or do I need some other files from rapydscript-ng?

assignment of list slice with omitted 'stop' causes compiler crash

test.pyj:

data = [0,1,2,3,4]
data[-2:] = [10]
print(data)
$ python2.7 test.pyj && python3.5 test.pyj 
[0, 1, 2, 10]
[0, 1, 2, 10]

Here's what I get:

$ rapydscript test.pyj
release/compiler.js:13057
                    self.property2.print(output);
                                  ^

TypeError: Cannot read property 'print' of undefined
    at release/compiler.js:13057:35
    at OutputStream.with_square (release/compiler.js:11766:19)
    at release/compiler.js:13054:24
    at OutputStream.with_parens (release/compiler.js:11755:19)
    at print_splice_assignment (release/compiler.js:13051:20)
    at AST_Splice.ρσ_anonfunc [as print] (release/compiler.js:15057:25)
    at ρσ_anonfunc (release/compiler.js:15356:35)
    at AST_SimpleStatement.ρσ_anonfunc [as print] (release/compiler.js:15057:25)
    at display_body (release/compiler.js:12059:26)
    at release/compiler.js:14693:33
$ rapydscript --version
rapydscript-ng 0.7.10

Help: compiler not working

[mardon86@archlinux bin]$ ./rapydscript
module.js:341
throw err;
^

Error: Cannot find module 'regenerator'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object. (/media/DATA/GITs/rapydscript-ng/tools/compiler.js:16:19)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)

fresh clone from git
node-5.10.0

Using RapydScript-ng in the browser

I'm submitting this issue in order to make contact with you, not knowing your email address. I'm the developer of glowscript.org, which uses Tsepkov RapydScript to permit users to write Python programs that generate real-time navigable 3D animations extremely easily. For example, the one-line program "box()" creates a WebGL canvas, displays a white cube at the origin, provides useful lighting, positions the camera so that the box fills the screen, and turns on mouse controls for zooming and rotating the camera. Programs can be written and run even on mobile devices. See the Example programs at glowscript.org.

I like very much the enhancements you have made and would like to use your version of RS, and like you I'm concerned that evidently Tsepkov now has little time to devote to improving RS. I had difficulties using standard RS in the client and have no interest in using it in a server or with node. I would be thrilled if you could tell me how to use your version of RS in the browser. Thanks much.

Bruce Sherwood ([email protected])

P.S. I taught at Caltech 1966-1969, then switched to college physics education, including the use of computers.

range issue?

The inner loops here are not executed, as the output just shows x 0, x 1, x2:

xx = range(3)
for x in xx:
    console.log('x',x)
    for y in xx:
        console.log('   y',y)
        for z in xx:
            console.log('      z',z)

Evidently the problem is that xx is an iterator, not a list. Both CPython and rapydscript do execute the inner loops. Is this a bug or a feature? It's the first bug report I've gotten since upgrading GlowScript to RS-NG.

named arguments

Calling a function with named argument is not working. It's working on the original rapydscript.

Welcome to the RapydScript REPL! Press Ctrl+C then Ctrl+D to quit.
Use show_js=False to stop the REPL from showing the compiled JavaScript.

def test(a,b,c):
... print('a=' + a + ', b=' + b + ', c=' + c)
...
...
---------- Compiled JavaScript ---------
function test(a, b, c) {
print("a=" + a + ", b=" + b + ", c=" + c);
}
---------- Running JavaScript ---------
test(1,2,3)
---------- Compiled JavaScript ---------
test(1, 2, 3);
---------- Running JavaScript ---------
a=1, b=2, c=3
test(a=1,b=2,c=3)
---------- Compiled JavaScript ---------
test(_$rapyd$_desugar_kwargs({a: 1, b: 2, c: 3}));
---------- Running JavaScript ---------
a=[object Object], b=undefined, c=undefined

modules are imported alphabetically instead of in import order

If I have a module say vyom/parser.pyj, and if it tries to do from vyom import utils, and vyom/utils.pyj exists, I get:

20:11:49 watchdog.1    | main.pyj:./vyom/parser.pyj:The symbol "utils" is not exported from the module: vyom (line: 6, col: 0, pos: 76)
20:11:49 watchdog.1    | 
20:11:49 watchdog.1    | Error
20:11:49 watchdog.1    |     at ImportError.__init__ (lib/compiler.js:2490:26)
20:11:49 watchdog.1    |     at ImportError.__init__ (lib/compiler.js:2525:78)
20:11:49 watchdog.1    |     at new ImportError (lib/compiler.js:2521:44)
20:11:49 watchdog.1    |     at import_error (lib/compiler.js:5701:23)
20:11:49 watchdog.1    |     at import_ (lib/compiler.js:5891:33)
20:11:49 watchdog.1    |     at lib/compiler.js:5450:32
20:11:49 watchdog.1    |     at lib/compiler.js:5169:28
20:11:49 watchdog.1    |     at lib/compiler.js:7211:31
20:11:49 watchdog.1    |     at parse (lib/compiler.js:7266:14)
20:11:49 watchdog.1    |     at do_import (lib/compiler.js:5798:21)
20:11:49 watchdog.1    | make[1]: *** [../static/charm.js] Error 1
20:11:49 watchdog.1    | main.pyj:./vyom/parser.pyj:The symbol "utils" is not exported from the module: vyom (line: 6, col: 0, pos: 76)
20:11:49 watchdog.1    | 
20:11:49 watchdog.1    | Error
20:11:49 watchdog.1    |     at ImportError.__init__ (lib/compiler.js:2490:26)
20:11:49 watchdog.1    |     at ImportError.__init__ (lib/compiler.js:2525:78)
20:11:49 watchdog.1    |     at new ImportError (lib/compiler.js:2521:44)
20:11:49 watchdog.1    |     at import_error (lib/compiler.js:5701:23)
20:11:49 watchdog.1    |     at import_ (lib/compiler.js:5891:33)
20:11:49 watchdog.1    |     at lib/compiler.js:5450:32
20:11:49 watchdog.1    |     at lib/compiler.js:5169:28
20:11:49 watchdog.1    |     at lib/compiler.js:7211:31
20:11:49 watchdog.1    |     at parse (lib/compiler.js:7266:14)
20:11:49 watchdog.1    |     at do_import (lib/compiler.js:5798:21)
20:11:49 watchdog.1    | make[1]: *** [../static/charm.js] Error 1

If I import vyom.parser from vyom/utils.pyj, it works well. If I do not do such imports, and look at generated code, both utils and parser are included, and from other modules I can import both. They are defined in alphabetical order in the compiled js file, so I can see why it is failing.

I could have lived with this, but even if I try to import inside a function, instead of global import, which is the goto solution for circular import problems in regular python, even then it complains and fails.

May be at import time we should not check for other modules, which should only have one side effect: inability to decide if foo() is a function call or class declaration. I suggest we live with that, remove the check if module exists or not, and I can explicitly write new foo() when needed.

Hi Kovid

In web browse compiler
I encounter a problem with list comprehension
lst = [x fof x in range(5)]
I get

ReferenceError: Symbol is not defined

Regards

Using RapydScript-ng in cordova

Hi @kovidgoyal im trying to use rapydscript-ng (embedded) in cordova. It works on browser platform target, but doesnt work on the android platform target.
Here is the code:
rsng-cordova-01

It works on both platform if i use the original RapydScript.
Here is the code:
rsng-cordova-02

How to solve this ? am i missing simething ? Thx.

Technical ebook user interface

I agree that "sweet spot" is an excellent description of rs-ng.

I clicked on your photo and was led to your brief bio, where I was reminded that you have a Ph.D. in physics from Caltech. My first position as a physicist was at Caltech in 1966-1969, where I was in a group doing experimental particle physics at SLAC and the Berkeley Bevatron, with lots of computer involvement, and teaching intro physics using as textbook the Feyman Lectures on Physics, which was a fabulous experience and which led to leaving particle physics for physics education, including the use of computers. The textbook "Matter & Interactions" that Ruth Chabay and I have written was strongly influenced by the Feynman textbook.

Like you, I read a lot (in multiple languages), and for many years almost all my book reading has been of ebooks, especially Kindle books, not only on Kindle readers. Your physics and ebook experience suggest that you might be interested in addressing what I see as a serious problem with ebooks on technical matters, including textbooks. It is something that someone ought to be willing pay a significant amount for a solution. The issue is that ebooks work fine for many kinds of books that are read pretty much linearly, such as novels and biographies and histories, but the current user interface is pretty bad for studying technical books, where one continually flips forward and back.

At the start of the GlowScript project five years ago I had lots of programming experience but knew nothing about web programming. I made the deliberate choice to read books on web programming in ebook form, to experience something of the reactions students might have to electronic textbooks. What I found was that it is difficult to flip forward and back, looking for something like "the page that had a predominantly red figure at the upper right" and to return easily to the original page. Yes, the ebook has a search capability, but it's not a Google-like search, it's a search for a specific character string, which is often nearly useless. The closest approach I've seen so far to a good interface is the one on current Kindle devices, where moving back and forth with easy return to the original page is sort of okay but not great. In a long book with a scroll bar, it would be better for the slider to embody acceleration, to make it easy to make small moves, rather than a small motion jumping several pages. Etc.

The point is, it looks like no one has thought seriously about what the user interface ought to look like for technical books. I'm guessing it could be much better than paper books, but that's not the current situation. There's a special concern about textbooks, because there seems to be a lot of student resistance to etextbooks despite their far lower price, due I would guess to the awkwardness to studying an etextbook.

You of all people have the skill set needed to make a far better user interface for technical use. Have you already thought about this?

I'll mention that Ruth and I would love to include GlowScript VPython 3D animations in the next (5th) edition of our textbooks, which is another reason why we're interested in etextbooks being attractive to students. A colleague has already done some little experiments with this.

Bruce
[email protected]

Class variable?

Thanks to being told about "--bare", I'm close to building a library, but in my Python program I have a class variable (a list) which is omitted from the resulting JS. I see in the README how to make a class method (@staticmethod), but I don't see how to make a class variable.

abs, min, max

Hi @kovidgoyal I looked into baselib.pyj, and found these functions:

def abs():
    return Math.abs
def max():
    return Math.max
def min():
    return Math.min

I think they should be something like:

def abs(x):
    return Math.abs(x)
def max(x):
    return Math.max(x)
def min(x):
    return Math.min(x)

CMIIW. What do you think ?

format, count...are not functions

Hello Kovid,

I experienced some problems with string methods.
Here is an example with the count, but it is the same with format
Can you help me ?

Regards

h-h-h".count();
---------- Running JavaScript ---------
TypeError: "h-h-h".count is not a function
at :1:9
at Object.exports.runInContext (vm.js:44:17)
at runjs (/home/salvatore/applications/rapydscript/node_modules/rapydscript-ng/tools/repl.js:247:25)
at compile_source (/home/salvatore/applications/rapydscript/node_modules/rapydscript-ng/tools/repl.js:285:9)
at push (/home/salvatore/applications/rapydscript/node_modules/rapydscript-ng/tools/repl.js:296:26)
at Interface. (/home/salvatore/applications/rapydscript/node_modules/rapydscript-ng/tools/repl.js:309:23)
at emitOne (events.js:90:13)
at Interface.emit (events.js:182:7)
at Interface._onLine (readline.js:211:10)
at Interface._line (readline.js:550:8)

Embedded RapydScript test fails

When I try the test of embedded RapydScript shown below, I get errors in both Firefox and Chrome.

Firefox:
Error: Unexpected token punc <<:>>, expected punc <<(>>          <embedded>:1:0
KL.CB   DocumentNotifier.onLoadDocument exc: Unknown window      tracer.js:22:0

Chrome:
Uncaught ReferenceError: ρσ_bool is not defined      VM575:9,  Object.defineProperties(ρσ_bool, {

-------------------------------
I added the statement "<meta charset="UTF-8">" to prevent other errors that occurred:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"> 
        <title>Test embedded RapydScript</title>
        <script src="https://kovidgoyal.github.io/rapydscript/repl/rapydscript.js"></script>
        <script>
var compiler = RapydScript.create_embedded_compiler()
var js = compiler.compile("def hellow_world:\n a='RapydScript is cool!'\n print(a)\n alert(a)")
window.onload = function() {
    document.body.textContent = js
    eval(js)
    eval('hello_world()')
}
        </script>
    </head>
    <body style="white-space:pre-wrap"></body>
</html>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.