:crescent_moon: A language that compiles to Lua
Repo leafo/moonscript, read from GitHub 1 d ago. leafo has not joined Take My Repo.
The LPeg parser has been replaced. The grammar is defined in moonscript/parse/grammar.moon and compiled by pgen into a native C module, moonscript.parse.native. A pure Lua version of the same grammar is included as moonscript.parse.slow, a drop-in replacement for the native module.
Parsing is around 5x faster:
| Interpreter | LPeg parser | New parser | Speedup |
|---|---|---|---|
| Lua 5.1.5 | 0.947s | 0.180s | 5.3x |
| LuaJIT 2.1 | 0.817s | 0.141s | 5.8x |
(Parse time for a 405 file, 58,296 line corpus, best of 5 passes.)
The parser produces the same syntax trees as the LPeg grammar. Other changes:
<message> at line <n>, column <m>: followed by the offending line and a ^ marker, replacing Failed to parse: [<n>] >> <line>. Anything matching on the old error text will need updating.moonscript.parse no longer exports build_grammar and extract_line, and the moonscript.parse.util, moonscript.parse.literals and moonscript.parse.env modules have been removed.MOONSCRIPT_PARSER environment variable is no longer used.moonscript.errors and bin/moon-tags use it for parsing unrelated to MoonScript source.moonc --correlate writes output where the line numbers of the generated Lua match the line numbers of the source, as closely as possible, so errors and stack traces point at the right line without a rewriter. The option is also available as correlate: true in the compile options to moonscript.base functions like to_lua and loadstring. (#312)moonc - (read from stdin) can now be combined with other flags, such as --lint, -o, -T, -X, --transform and --correlate. It can't be used with --watch or --output-to.failed to compile: <message> at line <n>, column <m>: followed by the offending line and a ^ marker, replacing Compile error: <message> and [<n>] >> <line>.moonscript.cmd.args module has been removed.false instead of nil in the name slot of the syntax tree, which fixes unpack dropping the trailing class fields on Lua 5.5.This update includes a bunch of syntax bug fixes and cleanups, with a few new features and an enhanced linter. This will be the last release using LPeg, future versions will use the new parser.
A function argument can now be written as a table literal to destructure the value passed in. The destructuring patterns are the same ones supported by assignment, including nested patterns, numeric keys, and @field targets:
dist = ({x: x1, y: y1}, {x: x2, y: y2}) -> math.sqrt (x2 - x1)^2 + (y2 - y1)^2 class Point new: ({x: @x, y: @y}) => render = (name, {:width, :height}, scale=1, ...) -> print name, width, height, scale, ...
The argument becomes an internal name and the fields are unpacked at the top of the function body:
render = function(name, _arg_0, scale, ...) local width, height width, height = _arg_0.width, _arg_0.height if scale == nil then scale = 1 end return print(name, width, height, scale, ...) end
Destructured arguments always declare fresh locals, so a name in the pattern shadows an enclosing local of the same name instead of assigning to it.
Argument initialization now happens in the order the arguments are written, so a default value can reference a name that an earlier argument destructured:
scaled = ({:base}, amount = base * 2) -> base + amount
Because the destructured names are bound at the top of the body, a name in a pattern can not collide with another argument. ({:a}, a) -> and ({:self}) => are now compile errors.
Destructuring can now be used mixed in with other names in multiple assignment (#367, #304):
num, {:message} = two_values! head, {:content}, tail = mix! {value: built}, {:status} = builder\build!
Previously the assignment was split into separate statements, which broke destructuring output.
The names extracted by a destructuring pattern are now checked with the same rule the parser uses for assignment targets. @@class_field, index expressions, and slices are now allowed:
{x: obj.a, y: obj["b"], z: @prop, w: @@cls_prop} = t
Destructuring into something that can never be assigned to is now a compile error instead of generating broken code:
{foo!} = thing reports Can't destructure into chain ending in call{...} = thing reports Can't destructure into '...'The linter's checks are now organized into named stages: global_access, unused, constant_assign, and import_overwrite. Every stage runs by default. moonc --lint-stage limits reporting to the named stage, and --exclude-lint-stage reports everything but the named stage. Both options can be repeated, and they can not be combined.
moonc -l --lint-stage global_access --lint-stage unused . moonc -l --exclude-lint-stage import_overwrite .
import_overwrite reports an import that clobbers a name that is already bound in scope:
insert = "hello" f = -> import insert from table -- import overwrites existing binding `insert`
constant_assign reports writing to a name that is tagged as constant. In this version, only the names created by import are tagged as constant. For this release, constant names are only checked in the linter. In the future we will make constant violation a compiler error.
import insert from table insert = 5 -- assigning to constant `insert`
moonc --lint-format compact writes one line per issue in the familiar file:line:column: message shape, with the stage name appended, for editors and tools that parse compiler output (#465):
$ moonc -l --lint-format compact lint_example.moon
lint_example.moon:7:5: accessing global `my_nmuber` [global_access]The moon module has four new functions, documented in the standard library reference:
is_class(value) tests if a value is a MoonScript class tableis_instance(value) tests if a value is an instance of a MoonScript classis_instance_of(value, cls) tests if a value is an instance of cls or any of its parents. It throws an error if value is not an instanceis_subclass_of(cls, parent) tests if cls inherits from parent. A class is not a subclass of itself. It throws an error if cls is not a classUnlike the old is_object, these can tell classes, instances, and __base tables apart.
is_object is now deprecated. It returns truthy for instances, classes, and __base tables, so it can not be used to distinguish them.
moon.type no longer returns the class object for a classmoon.type now returns the string "class" when given a class, and it only returns the class object for actual instances. Previously a class returned itself, and a __base table returned the class it belonged to, which made it impossible to tell an instance from the class it came from.
class MyClass type MyClass! -- MyClass (unchanged) type MyClass -- "class" (was MyClass) type MyClass.__base -- "table" (was MyClass)
moonscript.utilThese are internal helpers that were never documented, but they were reachable:
util.moon.type is now util.mtype, to avoid the confusion with the type function in the moon moduleutil.moon.is_object removed, replaced by util.moon.is_class and util.moon.is_instanceutil.moon.is_a removed, replaced by is_instance_of in the moon moduleThe compiler now knows Lua's operator precedence when writing out an expression, and it adds parentheses when a nested expression would otherwise be regrouped by the surrounding operators. String interpolation is the most common way to get a nested expression, and it was silently generating the wrong math (#320):
x = 10 / "#{b}.5"
Before:
local x = 10 / tostring(b) .. ".5"
After:
local x = 10 / (tostring(b) .. ".5")
Because .. is right associative in Lua, an interpolated string on the left hand side of a .. is grouped as well. This is observable through the __concat metamethod:
prefix = "id: #{id}, " .. rest
Before:
local prefix = "id: " .. tostring(id) .. ", " .. rest
After:
local prefix = ("id: " .. tostring(id) .. ", ") .. rest
The check for whether a value needs to be wrapped in parentheses did not account for the prefix operators #, -, not, and ~, which parse greedily. An update assignment or a switch case with one of them on the left would compile to the wrong grouping (#457):
count -= #datum + 1 total *= -x + 1 flag and= not a or b
Before:
local count = count - #datum + 1 local total = total * -x + 1 local flag = flag and not a or b
After:
local count = count - (#datum + 1) local total = total * (-x + 1) local flag = flag and (not a or b)
_When an expression appears where a statement is expected, the compiler assigns it to a throwaway variable. It used to use the name _, which would clobber a variable of that name in the user's code (#309). It now uses an autogenerated _scrap_N name.
_ = 5 tbl.field print _
Before:
local _ = 5 _ = tbl.field return print(_)
After:
local _ = 5 local _scrap_0 = tbl.field return print(_)
local in a class body is hoistedA local declaration is now hoisted to the top of the class body, so that methods defined on the class will have the local variable in scope. Previously only the names from regular assigns were hoisted.
class Counter local cache update: => cache or= "something..."
continue in a loop body generated invalid Lua (break was followed by more statements)a, b = x\some_method and other assignments of a single complex value to multiple names silently dropped every name after the first\stub without a base crashed the compiler with an internal error. Inside a with block it now uses the with value, and outside of one it reports Short-colon syntax must be called within a with block (#428)continue outside of a loop is now a compile error with a line number instead of an internal error with a tracebackif, switch, for, while, do, with, or comprehension declared the names in the wrong scope (#449, #411, #391, #451)..., nil, not thing, #thing, or a table literal, generated invalid Luamoonc --version which reported missing argument instead of printing version (#471)The static binaries now report build information with --version:
moon and moonc now use argparse for argument parsing, providing better help messages via --help and more robust option handling-e/--execute flag to moon - Execute MoonScript code directly from the command line:
moon -e "print 'Hello World'"
--transform option for moonc - Allows custom AST transformations before compilation by specifying a module that receives and returns the syntax tree- (stdin) handling - Now properly enforces that - must be the only argument-w is now also available as --watch-l is now also available as --lint-t is now also available as --output-to{:func} pattern)--lapis flag)--include-line flag)--no-header flag)moon.p() now prints multiple arguments - Pass multiple values and each will be dumpedutil.dump shows class names - When dumping objects, the class name is displayed (e.g., <MyClass>{...})@then or @@then) now compile correctly using bracket notation instead of invalid self.thenimport - Semicolons are now correctly inserted when the next line starts with (, preventing parsing ambiguitya[func()].x += 1 now correctly lift the index expression to avoid double evaluationmoon now exits with code 1 when the executed script failsmoonc - - Reading from stdin now works correctlyprint file, time in watcher codedump.tree returns string - Now returns the string instead of printing directlysplat.moon to use argparse, added --strip-prefix optionWindows binary: https://github.com/leafo/moonscript/releases/tag/win32-v0.5.0
Function calls with parentheses can now have free whitespace around the
arguments. Additionally, a line break may be used in place of a comma:
my_func( "first arg" => print "some func" "third arg", "fourth arg" )
Just like the function all update, function argument definitions have no
whitespace restrictions between arguments, and line breaks can be used to
separate arguments:
some_func = ( name type action="print" ) => print name, type, action
elseif can be used part of an unless block (nymphium)unless conditional expression can contain an assignment like an if statement (#251)moonc watch mode (ChickenNuggers)else could get attached to wrong if statement (#276).moon (Gskartwii)You can now find windows binaries through GithHub's releases. See win32-v0.4.0
supersuper now looks up the parent method via the class reference, instead of a
(fixed) closure to the parent class.
Given the following code:
class MyThing extends OtherThing the_method: => super!
In the past super would compile to something like this:
_parent_0.the_method(self)
Where _parent_0 was an internal local variable that contains a reference to
the parent class. Because the reference to parent is an internal local
variable, you could never swap out the parent unless resorting to the debug
library.
This version will compile to:
_class_0.__parent.__base.the_method(self)
Where _class_0 is an internal local variable that contains the current class (MyThing).
Another difference is that the instance method is looked up on __base instead
of the class. The old variation would trigger the metamethod for looking up on
the instance, but a class method of the same name could conflict, take
precedence, and be retuned instead. By referencing __base directly we avoid
this issue.
super can now be used on class methods. It works exactly as you would expect.
class MyThing extends OtherThing @static_method: => print super!
Calling super will compile to:
_class_0.__parent.static_method(self)
The scoping of super is more intelligent. You can warp your methods in other
code and super will still generate correctly. For example, syntax like this
will now work as expected:
class Sub extends Base value: if debugging => super! + 100 else => super! + 10 other_value: some_decorator { the_func: => super! }
super will refer to the lexically closest class declaration to find the name
of the method it should call on the parent.
with blocks used incorrect ref (#214 by @geomaster)with block would generate two return statements (#208)return or break in a continue wrapped block would generate invalid code (#215 #190 #183)moon command line script rewritten in MoonScriptmoonscript.parse.build_grammar function for getting new instance of parser grammar