Shop OBEX P1 Docs P2 Docs Learn Events
SMS - Automatically convert Pascal to Java script and run it on a P2 — Parallax Forums

SMS - Automatically convert Pascal to Java script and run it on a P2

As soon as Heater and the gang does the[color] impossible[/color] LOL and gets's JavaScript running on the Propeller Chip 2(Prop2) , I will start working with SMS(Smart Mobile Studio) to make a few JavaScript examples for Prop2

Heater Project is here:
http://forums.parallax.com/discussion/163323/c-c-on-the-p2-and-nano-fpga#latest

SMS : You can write your code in Smart Pascal(modern version of Pascal) or you can take Pascal code(Delphi, Lazarus) and convert it to JavaScript. There is a free version command line version of the compiler available here:

http://smartmobilestudio.com/2014/06/04/giving-back-community/

YouTube Example:

SMS currently supports the Espruino Microcontroller project http://www.espruino.com with a few built in examples (node.js , Lesson 1 - Onboard LEDs, Lesson 2 - LED Stick)

SMS also supports Raspberry Pi and node.js (Built in example - Simple server)

My personal goal for the the Internet of things\Web of things is to use a Propeller chip\Raspberry Pi combo and use either

1. SMS for JavaScript, API, Cloud(planned for later this year) PhoneGap / Apache Cordova, development etc.

2. Lazarus with opensource components such as (https://www.tmssoftware.com/site/blog.asp?post=313 ) for the client or server side development

Example: TMS LCL HW Pack for Raspberry Pi

https://www.tmssoftware.com/site/tmslclhwpack.asp

3. Lazarus with Paid components such as : Raspberry Pi 2 and TMS Cloud Pack

Example: https://www.tmssoftware.com/site/blog.asp?post=313

4. Using a Propeller chip with SMS and a CHIRIMEN(open source hardware) board (prorgamable in HTML5, JavaScript etc )

http://mozopenhard.mozillafactory.org/

The list goes on however, the one thing that's for sure is that to use a Proper Chip 2 and be able to communicate with the rest of the world , JavaScript is essential!!.

Go Pascal Go :)

«13

Comments

  • Heater.Heater. Posts: 21,230
    edited 2016-01-19 16:41
    And I thought I was bonkers mad just contemplating getting a JS engine running on the P2.

    :)

    The Problem with the plan is that the Pascal to JS compiler is closed source and Windows only. Bit of a non-starter for me I'm afraid.
  • re:Pascal to JS compiler is closed source and Windows only. Bit of a non-starter for me I'm afraid.

    Actually you are correct however, I was in no way posting this specifically for you (from past discussions we already know you not a fan of Pascal) other than to give you credit for the essential Prop 2 JavaScript Project that you currently doing or planning. Also, without your(and the other Prop heads) work and support on JavaScript, other projects like this one are impossible .

    ** Just for the record There are actually other very productive programmers out there in the world that use Pascal and like it . Even Skype was written in Pascal(Delphi) :) .

    re:Windows only
    the current version of SMS was written with Delphi but it's currently going through a re-write with Free Pascal(open source) \ Lazarus (open source) which means that it will run on other platforms(iOS , Linux etc.. ) very soon. Although the main JavaScript engine is closed source it is based on DWscript which is open source.

    DWScript:
    https://bitbucket.org/egrange/dwscript

    Licensing
    DWScript is released under Mozilla Public License 1.1 which, in short, means that it's free to use in open or closed source projects, free or commercial, provided you honor the following requirements: * any application that makes use of DWScript, or is compiled by DWScript should "conspicuously" include a reference to DWScript in its credits, and include or link to the DWScript source files. * modification to the source have to be made public under MPL. If you can't or don't want to satisfy the above requirements, contact the project manager for use under other license schemes.





  • jmgjmg Posts: 15,175
    Another approach is to take FPC and add a P2 Code generator.

    Seems there are a number of stable code generators already, and their ease-of-add has improved over time.

    https://en.wikipedia.org/wiki/Free_Pascal
  • Also re:Pascal to JS compiler is closed source


    Is is it so important when the compiler spits our JavaScript that you have complete access to?

  • Heater.Heater. Posts: 21,230
    Bob,

    Well, apart from the syntax and semantics the Pascal language is just fine. :)

    More seriously a couple of our companies key software components are written in Pascal. Originally for Delphi, now we use FPC. It's no end of trouble getting it to compile and run here and there and a pain to add new features we want. A serious road block to progress.
    Skype was written in Pascal
    I'm not sure that is a recommendation :)
    Also re:Pascal to JS compiler is closed source

    Is is it so important when the compiler spits out JavaScript that you have complete access to?
    Depends what you want to do.

    I'm sure the JS it spits out is unreadable gibberish that one would not to maintain afterwards. Like Emscripten does for C/C++ transpilation to JS.

    If one could do a one off transpilation that produced nicely formatted, readable code, with all the comments in place then one might not have a problem.

    But, I'm guessing the idea here is to develop in Pascal, then have the opportunity to run in the browser or under node or wherever. At that point its a closed source compiler as much as any commercial C/C++ compiler.



  • Bob Lawrence (VE1RLL)Bob Lawrence (VE1RLL) Posts: 1,720
    edited 2016-01-19 19:01
    @ Heater
    re:I'm sure the JS it spits out is unreadable gibberish that one would not to maintain afterwards. Like Emscripten does for C/C++ transpilation to JS.


    Here's an example of the JavaScript output(just part of a sample) for a simple Node.js server
    ====================================================
    function Console() {
       var Result = null;
        Result = console; return Result
    };
    function http() {
       return require("http");
    };
    /// TNodeEventEmitter_listeners_result_object = class (TObject)
    ///  [line: 32, column: 3, file: NodeJS.events]
    var TNodeEventEmitter_listeners_result_object = {
       $ClassName:"TNodeEventEmitter_listeners_result_object",
       $Parent:TObject
       ,$Init:function ($) {
          TObject.$Init($);
       }
       ,Destroy:TObject.Destroy
    };
    /// TNodeSocket_address_result_object = class (TObject)
    ///  [line: 50, column: 3, file: NodeJS.net]
    var TNodeSocket_address_result_object = {
       $ClassName:"TNodeSocket_address_result_object",
       $Parent:TObject
       ,$Init:function ($) {
          TObject.$Init($);
       }
       ,Destroy:TObject.Destroy
    };
    /// TReadableStream_pipe_options_object_stream = class (TObject)
    ///  [line: 42, column: 3, file: NodeJS.stream]
    var TReadableStream_pipe_options_object_stream = {
       $ClassName:"TReadableStream_pipe_options_object_stream",
       $Parent:TObject
       ,$Init:function ($) {
          TObject.$Init($);
       }
       ,Destroy:TObject.Destroy
    
  • Heater.Heater. Posts: 21,230
    edited 2016-01-19 19:14
    Bob,

    Hard to tell from that. That code does not actually do anything.

    Any chance you could transpile a typical piece of example code? Say a function that implements the classic recursive Fibonacci sequence calculation?
    program fibonacci;
    
    function fib(n:integer): integer;
    begin
        if (n <= 2) then
            fib := 1
        else
            fib := fib(n-1) + fib(n-2);
    end;
    
    var
        i:integer;
    
    begin
        for i := 1 to 16 do
            write(fib(i), ', ');
        writeln('...');
    end.
    

    Also I forgot to say, Pascal is unreadable gibberish to me :)
  • rjo__rjo__ Posts: 2,114
    Nice way to warm up the audience Heater.

    It seems like the world is making it more difficult to get applications to work together. Is it going to be possible to... say send a javascript from the P2... to a utility running on your favorite computer and have that utility take the script and send out command line stuff?

    I haven't had a communications problem I couldn't solve, but the solutions are so ugly and limited, it makes me a little sick every time I have to do it.
  • Heater.Heater. Posts: 21,230
    edited 2016-01-20 02:46
    Not sure I understand what you want to do exactly rjo__ but...

    JS is just text. A JS program can be given JS as a string and run it with eval(). So in a pure JS world we might have:

    JS on the Propeller creates JS as a string, sends it to JS running on "favorite computer", which then evaluates it with eval() and returns the result back to the JS on the Propeller.

    In fact this is how people were sending data between a browser and a web server not long ago. Sometimes they still do.

    The problem with this is that you are now running arbitrary strings as code using eval(). A dangerous idea. To fix that Douglas Crockford invented Javascript Object Notation (JSON) which is basically a subset of Javascript syntax. JSON is the data definition syntax of JS without any executable logic. A JSON string is evaluated with JSON.parse() rather than run with eval().

    Often the JSON.parse() is hidden in you communications API so we might end up with code as simple as this:
    // The sending end...
    var data = {
        temperature: 23,
        pressure: 29.92,
        time: getTime()
    };
    serial.send("message", data);
    
    // The receiving end...
    serial.on("message", function (data) {
        if (data.temperature >= 100) {
            console.log("Boiling!");
        }   
    };
    

    Communications has never been so simple.



  • rjo__rjo__ Posts: 2,114
    Excellent. I have seen many references to json... but thought that it was new and probably a waste of my time. Apparently that was not exactly true:)

    Thanks
  • Heater.Heater. Posts: 21,230
    rjo__

    See http://json.org/

    It's kind of funny...

    In the browser API's we have XMLHttpRequest() which is used to make HTTP requests back to the server and exchange data. Obviously intended for using the XML format. Why XML? Because it was invented in the days of Java and XML was all the rage in the Java world.

    As it turns out Java is horrible and XML is worse. So web developers started exchanging Javascript source strings over XMLHttpRequest(). Which could be easily eval'ed in the browser into data objects. Very simple and fast. Pretty much what you described above.

    This usherd in the era of AJAX (Asynchronous JavaScript and XML) web applications. Even though there was no XML in use.

    Crockford formalized this and it soon got built into JS engines as "data = JASON.parse('someString')" and conversely "someString = JSON.stringify(data);"

    There are JSON parsers in pretty much every language now a days.
  • Heater.Heater. Posts: 21,230
    Bob,
    Even Skype was written in Pascal(Delphi) :)
    I just tried getting Skype to work on my Debian Linux PC. No luck. Used to work on 32 bit Debian 7 but no more on 64 bit Debian 8.

    Anyway, as I was fighting with it I noticed it's using Qt libraries.

    So I guess you did mean "was" as in "not any more".

    Aside: Also the Skype plugins for Chrome and Firefox wont install on that machine either. Skype is so hopeless.
  • These are annoying. I use the Smile out of Skype, and it's slowly getting borked...
  • @Heater
    re:So I guess you did mean "was" as in "not any more".

    Could be that they changed it but I just happened to pull a name from memory when I made the statement and my reference was this list at some point.

    https://jonlennartaasenden.wordpress.com/2014/11/06/famous-software-made-with-delphi/
  • Heater.Heater. Posts: 21,230
    edited 2016-01-20 22:44
    Spud,

    Yep. What happened?

    Back in 1998 or so, with a 486 PC, I found some internet "phone" software. Within minutes I was talking, from Finland, to a guy in Canada. Clear as a bell. Brilliant.

    What do we need to do this? :

    1) Read sound from microphone.

    2) Send sound over a socket to some IP address. Perhaps compressed or whatever.

    3) Get sound from socket and send it to sound card.

    4) The same in both directions.

    5) Optionally do all that for video.

    6) Optionally have each machine send/receive the data to multiple machines in a conference.

    All this needs is for you to give me your IP address. That is what email is for. Or perhaps you publish it on your web site.

    None of this needs, Skype, or Google Hangouts, or webex or whatever.

    An average code monkey could write such a thing for pretty much any platform in short order now a days.

    We don't need that ability to call actual phones on old fashioned phone networks. And all that other guff. It certainly does not need the bottleneck of central servers. The web is supposed to be distributed, right?

  • I have to disagree with you again @Heater...

    I do have one landline number in Berlin, Germany and one Landline number in California.

    Each number costs me $25 per YEAR and can be called by normal phones, still landing on my Skype on whatever computer I run Skype on.

    Since them Skype-numbers appear as land lines most people calling me from Germany do not pay anything to reach me, because usually Phone contracts in Germany do not charge for land line calls anymore.

    Here in the US of A things are - as usual - worse. I guess you never heard about the concept. In Germany it is so that the person initiating the call get charged for it. Not so in the US. Here BOTH parties get charged.

    So if my Mum gets a call from somebody on her AT&T landline she has to pay for it too. Same with cellular phones without flat rate. You will get charged minutes for getting called.

    Mum is paying around $40-$60 per month, even if not using the phone much. A usual cell phone cost also around $45 per month.

    I on the other hand pay $50 a YEAR for two numbers and maybe another $50 a year for outgoing calls over Skype to real phones.

    So I do actually really like the interconnection between Skype and the real phone world. Saves me and the company in Germany I work for hundreds of Dollars or Euros respective.

    Sometimes we have phone conferences over hours and basically for free.

    If some customer or in house employee need some help from me they just call the Berlin number and have no clue about talking to a guy in California. Actually I can (and did) move around here from one place to the other, go to a Parallax meeting in Rocklin or a nice resort at the ocean and nobody at the company in Germany is able to notice that.

    I think your problems with Skype are more in your head. Since Microsoft bought Skype a while ago your sub-consciousness does not allow you to install it correctly anymore. It is a MS product now. Maybe let somebody else install it for you?

    Just a guess.

    Mike
  • Heater.Heater. Posts: 21,230
    edited 2016-01-21 00:00
    msrobots,

    I am not about to deny that there are a bazillion phones in the world and that a way to call form one to another one across the world, at local rates, via the net is not desirable.

    However, I have a computer and internet connection, 20Mbits/sec in and out, that costs almost nothing. Slow by modern standards. The guys I want to talk to in other parts of the world also have computers and internet connections. Ergo, we don't need the phone network and all. It's just an unnecessary complication in the way.
    I think your problems with Skype are more in your head.
    Perhaps.

    My problem is that the Skype executable for Debian does not work. It did work a while back, before the latest OS upgrade. The Skype plugins for Chrome or Firefox do not work. It's not like I didn't try.

    You are very welcome to visit here and show me how to get this working. Perhaps we can hangout over a beer as well. Which would be nice.

    Which reminds me. The Google hangout thing works just fine on the same machine.
  • msrobotsmsrobots Posts: 3,709
    edited 2016-01-21 01:31
    well @Heater, good call on the beer, might be a interesting evening. But first you would have come here to California. I do not do snow. Second - debian - no clue - won't tell you to just use a windows box. I am polite.

    But back to the topic. You looked at the JavaScript implementation for that esp-whatever chip and where pondering about to build some JS engine for P2, right?

    How realistic is this? I really did enjoy our short trip together with JavaScript playing with the Editor thing. On a P2 this could be a nice language to have.

    Think about node on a Microcontroller build by @Chip. No need for a OS as such. Since you are the to go guy for emulator projects, you may have to do it. Who else?

    just dreaming. I even would be happy to run CPM on it.

    +12 degree C now, 5:35 in the evening. It is considered COLD by all people here.

    You really should visit that place in Rocklin. At least once in your life. Like that Hadsh(?) thing in Mecca.

    Enjoy!

    Mike
  • Bob Lawrence (VE1RLL)Bob Lawrence (VE1RLL) Posts: 1,720
    edited 2016-01-21 03:27
    re:Any chance you could transpile a typical piece of example code? Say a function that implements the classic recursive Fibonacci sequence calculation?
    program fibonacci;

    function fib(n:integer): integer;
    begin
    if (n <= 2) then
    fib := 1
    else
    fib := fib(n-1) + fib(n-2);
    end;

    var
    i:integer;

    begin
    for i := 1 to 16 do
    write(fib(i), ', ');
    writeln('...');
    end.

    OK I can try it but I don't know where you got this or dreamed it up LOL but it doesn't look right. If it doesn't
    compile in regular Pascal it won't compile to JavaScript in Smart Mobile Studio. Regardless, I'll give it a shot tomorrow morning. Hopefully my home or car won't blow up LOL
  • Heater.Heater. Posts: 21,230
    Sure it compiles with regular Pascal...
    $ cat fibo.pas 
    program fibonacci;
    
    function fib(n:integer): integer;
    begin
        if (n <= 2) then
            fib := 1
        else
            fib := fib(n-1) + fib(n-2);
    end;
    
    var
        i:integer;
    
    begin
        for i := 1 to 16 do
            write(fib(i), ', ');
        writeln('...');
    end.
    
    $ fpc fibo.pas
    Free Pascal Compiler version 2.6.4+dfsg-4 [2014/10/14] for x86_64
    Copyright (c) 1993-2014 by Florian Klaempfl and others
    Target OS: Linux for x86-64
    Compiling fibo.pas
    Linking fibo
    /usr/bin/ld.bfd: warning: link.res contains output sections; did you forget -T?
    19 lines compiled, 0.1 sec 
    
    $ ./fibo
    1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...
    $
    

    I did not dream it up. It's a standard exercise everyone does when first learning to program in pretty much any language.

    See here: http://progopedia.com/example/fibonacci/58/
    Or variants for other Pascal dialects linked to from the top of that page.
  • Heater.Heater. Posts: 21,230
    msrobots,

    To run some of the little JS interpreters on the P2 only requires we can compile them with prop-gcc.

    The Epruino engine, used on the ESP, may be a bit too big to fit in the HUB but there are others.

    Would the performance be acceptable? I have no idea, in JS all numbers are 64 bit floats so that is a bottleneck. I think the Espruino cheats a bit here by using 32 bit floats.

    As far as I can tell the Espruino is the only one that comes with a REPL for live editing of running code.

    CPM is almost certain to come to the P2.
  • Now I nail it down as soon as I can,

    CPM checked - @Heater.
    ZOG ?

    Mike
  • Heater.Heater. Posts: 21,230
    Zog? Perhaps, maybe. Zog does not get us anything more than another way to run C/C++. Still needs an external compiler.
  • @ Heater

    re : Sure it compiles with regular Pascal...

    OK that's a good start. I see you used Free Pascal on Linux box. However, I just tried it with free SMS compiler and it compiled with errors. Screen shot attached. Now I have to figure out why it failed on such a simple piece of code . It's the first time I tried to compile something via command line and I'll have to see what I'm doing wrong and that means reading the instructions :( LOL

    597 x 206 - 11K
  • I tried this version:
    http://www.yanniel.info/2011/11/fibonacci-numbers-in-delphi.html
    function Fibonacci(aNumber: Integer): Integer;
    begin
      if aNumber < 0 then
        raise Exception.Create('The Fibonacci sequence is not defined for negative integers.');
    
      case aNumber of
      0: Result:= 0;
      1: Result:= 1;
      else
        Result:= Fibonacci(aNumber - 1) + Fibonacci(aNumber - 2);
      end;
    end;
    


    It compiled fine and produced this JavaScript file:
    var $R = [];
    var TObject={
    	$ClassName: "TObject",
    	$Parent: null,
    	ClassName: function (s) { return s.$ClassName },
    	ClassType: function (s) { return s },
    	ClassParent: function (s) { return s.$Parent },
    	$Init: function () {},
    	Create: function (s) { return s },
    	Destroy: function (s) { for (var prop in s) if (s.hasOwnProperty(prop)) delete s.prop },
    	Destroy$: function(s) { return s.ClassType.Destroy(s) },
    	Free: function (s) { if (s!==null) s.ClassType.Destroy(s) }
    };
    var Exception={
    	$ClassName: "Exception",
    	$Parent: TObject,
    	$Init: function () { FMessage="" },
    	Create: function (s,Msg) { s.FMessage=Msg; return s }
    };
    function $New(c) { var i={ClassType:c}; c.$Init(i); return i };
    function Fibonacci(aNumber) {
       var Result = 0;
       if (aNumber<0) {
          throw Exception.Create($New(Exception),"The Fibonacci sequence is not defined for negative integers.");
       }
       switch (aNumber) {
          case 0 :
             Result = 0;
             break;
          case 1 :
             Result = 1;
             break;
          default :
             Result = Fibonacci(aNumber-1)+Fibonacci(aNumber-2);
       }
       return Result
    };
    
    
  • Heater.Heater. Posts: 21,230
    Yeah, I think we need to import "crt" or whatever it is that defines the I/O functions-

    I can't remember the syntax for that. "import", "include", "with", "use", "require" ?

    That JS does not looks so bad.



  • @Heater

    re:That JS does not looks so bad.

    It's certainly readable however, if you need Code obfuscation, there is an option to do that.

    What are the advantages of using SMS(other that one likes to program in Pascal) over just using pure JavaScript and HTML5?
    ============================================================================
    From the Webite:

    Object Pascal + HTML5 = Awesome!

    Smart Mobile Studio delivers unprecedented JavaScript power through it’s advanced compiler technology and cleverly crafted RTL architecture. By authoring your applications in Smart Pascal, the compiler is able to generate true object-oriented JavaScript with all the benefits of traditional languages. Finally you can enjoy all the cool stuff C++, C# and Object Pascal programmers have at their disposal — but in the browser. No plugins, no special extensions. Just pure HTML5 and JavaScript.

    The reason we are able to deliver this, is because our compiler is a real compiler – meaning that it generates code which makes use of a VMT (virtual method table) sculpted in JavaScript itself. It is the VMT that makes it possible to have classes and interfaces, and further virtual class methods which you can override and abstract.

    What we did was take a real compiler and replaced the
    assembler generator with our JavaScript generator

    Worried about bloat? Dont be. The compiler generates human readable code, with no dependencies and no fuzz. So in short: finally JavaScript developers can enjoy true OOP in their projects, while Delphi developers gain access to the incredible reality that is Javascript and HTML5. Here are some of the features Smart Mobile Studio brings to JavaScript:

    Classes
    Partial classes
    Class helpers
    Records
    Record helpers
    Lambdas
    Type checking
    RTTI
    Inheritance
    Polymorphism
    Property Accessors
    Virtual and abstract methods
    Private, Public and Protected members
    True JavaScript visual components
    True browser independence
    And naturally, the generated JavaScript is 100% pure! No dependencies, no plugins, extensions or “surprisingly” massive libraries – just your Smart Pascal code compiled into raw JavaScript. Lean, mean and fast! Your code now runs on any platform, in any HTML5 compliant browser – and with Phonegap you can even go native with 3 simple steps. That’s pretty cool!

    :https://jonlennartaasenden.wordpress.com/products/smart-mobile-studio/

  • jmgjmg Posts: 15,175
    "Finally you can enjoy all the cool stuff C++, C# and Object Pascal programmers have at their disposal — but in the browser. "

    That seems to be the key advantage which makes this less of an ideal fit for P2, which is still a Microcontoller, not a JS engine.

    A native Object Pascal compiler for P2 that can generate P2 compiled binaries, would have size and speed and stability advantages over an "install another engine", and this does not exclude you running some code in a Browser on another more suitable browser engine.
  • Heater.Heater. Posts: 21,230
    Why not just write your code is JS?

    If you want classes in JS here we go: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes

    I was tickled by the example fibo() code above. One of the key ideas of languages like Pascal is strict type checking. Which JS does not have. OK, fair enough, there have been many debates about that.

    But there in the Pascal code we see:
    if (aNumber<0) {
          throw Exception.....
    
    You mean Pascal's type system does not understand the whole numbers? And we have to check for that manually?

    Might as well write everything in a type free language.

    I think I'm tempted to run this transpiler over some 10's of thousands of lines of Pascal we have here. I'm not optimistic about the outcome.







  • jmgjmg Posts: 15,175
    edited 2016-01-21 22:26
    Heater. wrote: »
    But there in the Pascal code we see:
    if (aNumber<0) {
          throw Exception.....
    
    You mean Pascal's type system does not understand the whole numbers?
    Sure it does, see below.
    Heater. wrote: »
    And we have to check for that manually?

    Not if you actually USE the correct type to start with.

    Word / Cardinal / longword /QWord
    integer types Type 	Range 	Bytes
    Byte 	0 .. 255 	1
    Shortint 	-128 .. 127 	1
    Smallint 	-32768 .. 32767 	2
    Word 	0 .. 65535 	2
    Integer 	smallint or longint 	2 or 4
    Cardinal 	longword 	4
    Longint 	-2147483648 .. 2147483647 	4
    Longword 	0..4294967295 	4
    Int64 	-9223372036854775808 .. 9223372036854775807 	8
    QWord 0 .. 18446744073709551615 	8 
    
    Heater. wrote: »
    Might as well write everything in a type free language.

    Sure, but there is a cost to these 'any-numeric' languages, and that is run time speed & total code size on Microcontrollers.

    Which reinforces my point that JS is not a Microcontroller optimal language, and is best suited for Browser capable Microprocessors.
Sign In or Register to comment.