Git Product home page Git Product logo

opal's Introduction


Opal
Opal-Ruby 💛 JavaScript

Opal is a Ruby to JavaScript source-to-source compiler.
It also has an implementation of the Ruby corelib and stdlib.

Community:
Stack Overflow Backers on Open Collective Sponsors on Open Collective Slack Documentation
Code:
Gem Version Build Status Code Climate Coverage Status
Sponsors:
Nebulab: Open Source Fridays

Usage

See the website for more detailed instructions and guides for Rails, jQuery, Sinatra, rack, CDN, etc. https://opalrb.com.

Compiling Ruby code with the CLI (Command Line Interface)

Contents of app.rb:

puts 'Hello world!'

Then from the terminal

$ opal --compile app.rb > app.js # The Opal runtime is included by default
                                 # but can be skipped with the --no-opal flag

The resulting JavaScript file can be used normally from an HTML page:

<script src="app.js"></script>

Be sure to set the page encoding to UTF-8 inside your <head> tag as follows:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="app.js"></script></head>
  <body></body>
</html>

Just open this page in a browser and check the JavaScript console.

Compiling Ruby code from Ruby

Opal.compile is a simple interface to just compile a string of Ruby into a string of JavaScript code.

Opal.compile("puts 'wow'")  # => "(function() { ... self.$puts("wow"); ... })()"

Running this by itself is not enough; you need the opal runtime/corelib.

Using Opal::Builder

Opal::Builder can be used to build the runtime/corelib into a string.

Opal::Builder.build('opal') #=> "(function() { ... })()"

or to build an entire app including dependencies declared with require:

builder = Opal::Builder.new
builder.build_str('require "opal"; puts "wow"', '(inline)')
File.binwrite 'app.js', builder.to_s # must use binary mode for writing

Compiling Ruby code from HTML (or using it as you would with inline JavaScript)

opal-parser allows you to eval Ruby code directly from your HTML (and from Opal) files without needing any other building process.

So you can create a file like the one below, and start writing ruby for your web applications.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.opalrb.com/opal/current/opal.js"></script>
    <script src="https://cdn.opalrb.com/opal/current/opal-parser.js" onload="Opal.load('opal-parser')"></script>

    <script type="text/ruby">
      puts "hi"
    </script>

  </head>
  <body>
  </body>
</html>

Just open this page and check the JavaScript console.

NOTE: Although this is possible, this is not really recommended for production and should only be used as a quick way to get your hands on opal.

Running tests

Setup the project:

$ bin/setup

The test suite can be run using:

$ bundle exec rake

This command will run all RSpec and MSpec examples in sequence.

MSpec

MSpec tests can be run with:

$ rake mspec

Alternatively, you can just load up a rack instance using rackup, and visit http://localhost:9292/ in any web browser.

RSpec

RSpec tests can be run with:

$ rake rspec

Automated runs

A Guardfile with decent mappings between specs and lib/corelib/stdlib files is in place. Run bundle exec guard -i to start guard.

Code Overview

What code is supposed to run where?

  • lib/ code runs inside your Ruby env. It compiles Ruby to JavaScript.
  • opal/ is the runtime+corelib for our implementation (runs in browser).
  • stdlib/ is our implementation of Ruby's stdlib. It is optional (runs in browser).

lib/

The lib directory holds the Opal parser/compiler used to compile Ruby into JavaScript. It is also built ready for the browser into opal-parser.js to allow compilation in any JavaScript environment.

opal/

This directory holds the Opal runtime and corelib implemented in Ruby and JavaScript.

stdlib/

Holds the stdlib currently supported by Opal. This includes Observable, StringScanner, Date, etc.

Browser support

  • Internet Explorer 11
  • Firefox (Current - 1) or Current
  • Chrome (Current - 1) or Current
  • Safari (Current - 1) or Current
  • Opera (Current - 1) or Current

Any problems encountered using the browsers listed above should be reported as bugs.

(Current - 1) or Current denotes that we support the current stable version of the browser and the version that preceded it. For example, if the current version of a browser is 24.x, we support the 24.x and 23.x versions.

12.1x or (Current - 1) or Current denotes that we support Opera 12.1x as well as the last 2 versions of Opera. For example, if the current Opera version is 20.x, then we support Opera 12.1x, 19.x and 20.x but not Opera 15.x through 18.x.

Contributors

This project exists thanks to all the people who contribute. contributors

Versioning

Opal will broadly follow semver as a version policy, trying to bump the major version when introducing breaking changes. Being a language implementation we're also aware that there's a fine line between what can be considered breaking and what is expected to be "safe" or just "additive". Moving forward we'll attempt to better clarify what interfaces are meant to be public and what should be considered private.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Become a Backer Button

Sponsors

Donations

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

Become a Sponsor Button

Sponsored Contributions

Nebulab Logo

License

(The MIT License)

Copyright (C) 2013-2021 by Adam Beynon and the Opal contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

opal's People

Contributors

adambeynon avatar aekobear avatar alexdowad avatar bbatsov avatar elia avatar eregon avatar fazibear avatar fntz avatar ggrossetie avatar haileys avatar hmdne avatar iliabylich avatar janbiedermann avatar jelf avatar jeremyevans avatar jgaskins avatar jibi avatar kachick avatar kaiwren avatar mame avatar meh avatar mieko avatar mojavelinux avatar netoneko avatar ryanstout avatar takaram avatar vais avatar wied03 avatar yhara avatar ysakasin 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  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

opal's Issues

Check compiled Ruby for Javascript syntax errors.

This is really a must for debugging, not all browsers report syntax errors on included scripts, so we should really check the compiled code for them and raise a parse error.

We could either write our own javascript parser or use therubyracer to do a simple check. We should also be able somehow to infer the originating Ruby line.

This is required because it's really easy to write buggy inlined js (forgetting parenthesis and the like) and it would result in a LoadError when requiring said code.

Is there a way to alias a dependencies?

What I mean is, I want to use the call-me gem inside opal-browser, it's a pure Ruby gem so it should work without any changes with Opal, right now we're checking for /^opal-/ so, any good way to achieve this?

Make Builder work without Gemfile/Bundler/gemspec

Currently Builder must use a Gemfile to build a project. This should be simplified so that the Gemfile is only needed to build dependencies of the app/gem. The rake task should be sufficient to build a standalone app/gem.

Remove :BLOCK_GIVEN lexer token

Replace special :BLOCK_GIVEN lexer token and treat it as a normal method call. The generator nodes should handle its special case instead of the parser.

Implicit returns

Shouldn't it add a return to the last statement in the generated js?

Having to do

def title
  `return document.title`
end

is kind of ugly and unexpected for a rubyist instead of

def title
  `document.title`
end

Parser issues with parsing ? strings

> opal
>> ?l
/home/meh/.rvm/gems/ruby-head/gems/opal-0.3.15/lib/opal/parser/parser.rb:98:in `rescue in parse':  (Opal::OpalParseError)
parse error on value "?" ("?")
from parsing (irb):1

So yeah, it's completely missing I guess.

Use `ruby_parser`

Currently, opal has its own racc based parser for the lexing and parsing stage. Instead, opal should use ruby_parser, a ruby lib used to parse ruby code into s-expressions. The ruby_parser branch is the workings of doing this.

This new branch should also run in the browser, so we need to make sure ruby_parser is fully working with opal.

Optimise `break`

Currently break is implemented on top of throw to bubble a break up to the method that yielded the respective block. This is slow. It can be optimised by having break just return a special value out of the block and then each yield call should just check the return value to see if it is the break instance.

Pay attention about redefinition of undefined.

undefined can be set to something else, as in, undefined is a valid variable name, we should find a way to avoid redefinition of undefined.

The best way to go with this is to add var undefined at the beginning of each function, or find a better way to avoid cluttering up everything.

Implement compile time helpers.

Opal.object?, true if the object is a Ruby object, false otherwise.
Opal.native?, true if the object is not a Ruby object, false otherwise.
Opal.string?, true if the object is a JS string (or a Ruby string).
Opal.number?, true if the object is a JS number.
Opal.function?, true if the object is a function.
Opal.defined?, works like Ruby #defined? but uses typeof to do its job.
Opal.undefined?, checks if the value is undefined.
Opal.null?, checks if the value is null.
Opal.typeof, same as typeof.

super doesn't work with mixins.

>> module LOL; def initialize (nigger); puts "wat #{nigger} wat"; end; end
nil
>> class OMG; include LOL; def initialize; super("^_^"); end; end
nil
>> OMG.new
wat ^_^ wat
#<OMG:0x00000000c54158>
>> module LOL; def initialize (nigger); puts "wat #{nigger} wat"; end; end
Exception: Cannot call method '$inspect' of undefined

=> nil
>> class OMG; include LOL; def initialize; super("^_^"); end; end
=> #<Proc:0x0000000>
>> OMG.new
Exception: Cannot read property 'undefined' of undefined
    from OMG#initialize at /core/class.rb:12
    from OMG.new at (irb):1
=> nil

NativeArray to support Subclassing Arrays

Currently subclassing arrays breaks because subclass instances wont be real js arrays, therefore their length property will not update to reflect the true length. To fix this, js arrays will be instances of NativeArray, which is a ruby subclass of Array. NativeArray will re-implement all the methods that need auto updating .length properties with methods that assume they can update. This means that subclassing Array in ruby will give you methods that will check for the length property in relevant methods, and NativeArray will keep native js arrays nice and fast.

To summarise; NativeArray will re-implement around 10 Array methods that will fix this gap (and be faster than checking .length each time).

method_missing support for non-debug mode

Debug mode supports method_missing, but normal mode doesn't. method_missing is too slow to be on by default, so it will need to be opt-in as an option in the Rakefile for the gem/app.

rake opal fails in opal/examples/browser

commit 868146147

opal/examples/browser $  bundle exec rake opal --trace
** Invoke opal (first_time)
** Execute opal
rake aborted!
wrong number of arguments (1 for 0)
opal/opalite/opal/builder.rb:71:in `initialize'
opal/opalite/opal/rake/builder_task.rb:37:in `new'
opal/opalite/opal/rake/builder_task.rb:37:in `block in define_rake_task'
Tasks: TOP => opal

Optimising ivar reading

Currently, when compiling a method that accesses an instance variable, the ruby method:

def title
  @title
end

Will compile into (roughly) the following javascript:

function() { var self = this; if (self.title == undefined) { self.title = nil; }
  return self.title;
}

This if check is needed as returning a non-initialised instance variable should return nil. The check is needed every time the function is run as the opal compiler has no idea when it will first be run.

Proposition

The proposal is to, at compile time, gather a list of all ivar accesses inside a class and then on class definition set all these properties to nil on the prototype chain for the class constructor. This means that at runtime all instances of a class will have these ivars already set to nil.

Inheritance

As opal uses prototype inheritance anyway, these ivars will be carried into child classes as well.

Kernel#instance_variable_{get,set,defined?}

Using hasOwnProperty, the runtime can determine whether these ivars have actually been set, or have been carried through the prototype chain.

Benefits

The benefit would be, firstly, cleaner generated code which makes opal easier to debug. Secondly, method accessors using ivars will be faster as they will not need to check on property existence on every call. Finally, the reduced size of the generated javascript has obvious benefits.

New generated code:

function() { var self = this;
  return this.title;
}

Reduce opal.js file size

opal.js contains the runtime and core library built for the browser. Currently it measures at:

Raw: 124,141 bytes
minified: 56,707 bytes
gzipped: 12,735 bytes

The aim is to cut this just short of half in size to make opal as small as possible. The aim is to make opal.js 40kb to reduce the overhead considerations for mobile devices.

The speed_over_features branch should hold this. This issue is to hold any broken parts that arise from changes.

First change set: a9e2053

Implemente `#to_native` in the various objects.

#to_native should be the default way to get a native object from a Ruby object.

Object#to_native should return a JS object with the object instance variables as elements.
Array#to_native should return a map of self with #to_native called on every element that is a Ruby object.
Hash#to_native should return a JS object with as values #to_native called on every element that is a Ruby object.
NilClass#to_native should return undefined.

Remove js based parser

The js based parser (dev in core lib) should be removed and the opalite parser (ruby written + racc) should be compiled into js so that it runs inside browser. mass-args not causing it to compile correctly.

Symbols, we should really look a bit better into it.

I'm not so sure how much using js strings as symbols would improve speed.

While implementing some corelib stuff I noticed the absence of real symbols is making some methods implementation impossible.

In short, we should benchmark speed of both, and I sincerely would prefer to have Symbol back.

Symbols are a really important part in Ruby, it would be like disabling operator overload, a lot of libraries won't work and won't be able to be patched, because Symbol and String are the same thing.

I also am not really sure about the caching of strings improving our speed.

Have an $opal.global variable.

Which should be something on the lines of (function () { return this; })() in global scope, in this way you can easily access global constructors and such.

For instance, I need it in typed-array, where I build a string with the name of the array constructor and I'd have to use eval to get it, or use window which is only in the browser's scope.

Support Arg checking in debug mode

Debug mode should generate code for every method that checks if the correct number of arguments were given to the method. Default/production mode should not generate this code.

Interact/access javascript objects/methods

Currently Opal needs to wrap any native js construct (arrays, jquery instances, custom libraries etc) so they can be accessed in a ruby way - i.e. so we still get method_missing, "getter" and "setter" methods, operator overloading etc. Opal still needs a proper way to interact with js objects without using the backtik approach.

One solution is to use the :: construct to access javascript properties. For instance, to get an array length using its native length property, we could use:

[1, 2, 3, 4]::length           # => compiles to [1, 2, 3, 4].length

Instead of the method call version:

[1, 2, 3, 4].length             # => compiles to [1, 2, 3, 4].m$length()

Another approach is to make it obvious that we are running directly on top of javascript, and maybe make an "opalscript" branch which is more of a ruby syntax for javascript, rather than a ruby runtime on top of javascript. Method calls would follow perhaps Coffeescript's style where a call without args and parans is simply a property access.

Constant lookup sometimes checks wrong scope

When looking up constants in a class/module, the wrong scope is checked. const_get is used for all scope lookups, but really there should be an addition const_at function for checking just in the required context. For example, A::B, where A is looked up using const_get, but B should be looked up using const_at, where the search is more specific and does not bubble up to top level namespaces.

Implement typed arrays bridges.

While implementing the wrapper for XHR I found out there's an easy way to transfer and work with binary data, and it uses typed arrays.

So I started working on a bridging implementation.

Will report back on IRC to ask for some assistance in the class bridging operation.

It will also give (me) the chance to implement really fast wrapping stuff, it's also needed in WebGL.

Implement scoped constant lookup

Constant lookup should be done on scope instead of superclass chain. Makes constant lookup much faster (based on prototypes).

$runtime is not defined

Opal example works fine for me but if I try precompile ruby code (browser.rb) I get this error:
$runtime is not defined (in precompiled browrser.rb, I called browser.js)

I use HTML code like this:

<script src="../../extras/opal.js"></script>
<script src="../../extras/opal.dev.js"></script>    
<script type="text/javascript" src="browser.js"></script>

I've tried removing opal.dev.js, I've tried rquery.js (from homepage) but I always get the same error.

Any help? Thank you in advance.

The level of compatibility with ruby, pros & cons

Would like to discuss pros & cons of partially compatibility with the standard Ruby. As far as I understood there are no plans to do it 100% compatibile, if so - maybe it's worth to leverage this fact and turn lemons into lemonade.

This is not proposals, but just a rough thoughts and ideas, would like to see what do You think about it.

  1. Inheritance & Object Model:
    Maybe it's worth to leverage native JavaScript prototypical inheritance (with fixed self and added method_missing & super)?
    If this stuff will be fixed and it will be nicely wrapped - it may also be quite powerful and handy model.
    After all the Ruby Object Model is not an ideal (it doesn't support multiple inheritance for example).
    I'm personally would be quite satisfied with (fixed) JavaScript Prototypical model.
    And it probably gives more simple implementation code and better performance.
  2. Global variables:
    During 3 years of ruby I never used all this cryptic perlish stuff like $1 $&amp; $:< and so on. Also I never used global variables at all.
    In almost all situations they can be easily replaced with constants & singletons. Is there a need for this stuff?
  3. Maybe it's wort also to drop the Symbol class. I mean - leave the Symbol syntax(it's quite handy) but make it to define String instead of Symbol (because the only point of introducing it in Ruby was performance, but because in JS strings are immutable - there's no point of using it here).

There are some quite successful projects using this approach (CoffeeScript, Mirah, Boo).

This is only my subjective and personal opinion, and would be interesting what do You think about it?

Implement various bridges.

Module#define_method_bridge (target, name, alias = nil), defines a method that bridges arguments to a native js function.

Module#attr_accessor_bridge (target, *names), defines accessors to the target native attributes, same goes for reader and writer.

stdlib or corelib (Native and stuff)

I sincerely think Native should be in the corelib, same goes for the stuff I'm doing for typed arrays.

Practically all wrapper libraries will use Native and it's small anyway.

I think corelib should contain language related things, while stdlib should contain stuff that has nothing to do with the language itself.

Wanting to reduce the size of the resulting file should be a priority, but not this much IMHO, especially when including stdlib stuff is a pain in the ass.

Support #coerce

Does Opal support #coerce already?

Grepping for coerce doesn't show up anything, so I guess not.

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.