Skip to content
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
255 changes: 255 additions & 0 deletions docs/export-keyword.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@

# Export by Value

## Summary
Extend the `export` keyword to support values and functions as syntax sugar for constructing a table and returning it from a module.

## Motivation
Today, type aliases are able to be exported from a module using the `export` keyword.

```luau
export type Point = {x: number, y: number}
```

However, this mechanism is currently only supported by types.

Extending `export` to also support values and functions would provide a consistent way for users to expose a stable API from modules. Furthermore, static exports would allow for many future optimizations, such as cross-module inlining and constant folding.

## Design
Allow the `export` contextual keyword anywhere the `local` keyword may be used at the top level of a module, as well as within nested `do end` blocks. Attempting to export a variable outside the module scope will be a parse error.

Exported variables will count towards the local variable limit, as they can be optimized into locals by the compiler.

```luau
export version = "5.1"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also we can think about export const version = "5.1" syntax to make assignment to version a syntax error(or even make it default). In this case export local x can be symmetric syntax explicitly signaling x will be modified later.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly, since I made this RFC with the expectation that const would be rolled back (because the whole rationale for const was to fill the "can't reassign" gap immutable exports brought), I never had any plans for introducing const-ness to exported tokens. Now that const is here but immutable exports aren't, things are awkward.

I guess I can try to retrofit everything with const in mind, but my fear is the result is going to be a little "sore" since the features here are going to added in backwards.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only rational way to do this is to make export a keyword that goes before declarations like you've suggested. Functions/classes might have to be special-cased where they are always exported const, but that should be fine.


export function init()
-- TODO
end

do
local counter = 0

export function increment(): number
counter += 1
return counter
end
end
-- counter and increment not visible here

if foo then
export bar = 1 -- not allowed, syntax error
end
```

Just like local variable declarations, it is possible to export multiple variables, variables with type annotations, and uninitialized variables.

```luau
export settings: Settings = getSettings()
export a, b, c = 1, 2, 3
export d -- same as export d = nil
```

Exporting a variable with the same identifier twice is a parse error, regardless of the scope it was defined in.

```luau
export foo = 1
do
export foo = 2 -- syntax error
end
```

However, exporting a variable with the same identifier as another non-exported variable is allowed, following conventional lexical scoping and shadowing rules.

```luau
local function foo() return 1 end
export function foo() return 2 end -- exported, shadows foo

print(foo()) -- 2

local fruit = "apple"
export fruit -- exports fruit = nil, not "apple"
print(fruit) -- nil

export animal = "dog"
local animal = "cat" -- shadows animal, doesn't change export
animal = "bird"

print(animal) -- bird
```

### Desugared Form
Exporting variables desugars into assigning keys to a table that is then frozen and returned once the module scope ends.

```luau
export a = 1

-- desugars into

local _EXP = {}
_EXP.a = 1
return table.freeze(_EXP)
```

Exported variables can therefore be reassigned within the module after being declared. This allows for conditional exports and forward declarations.

```luau
export side = "heads"
if math.random(0, 1) == 1 then
side = "tails"
end

export f, g
function f()
g()
end
function g()
f()
end

-- desugars into

local _EXP = {}
_EXP.side = "heads"
if math.random(0, 1) == 1 then
_EXP.side = "tails"
end

_EXP.f, _EXP.g = nil, nil
function _EXP.f()
_EXP.g()
end
function _EXP.g()
_EXP.f()
end

return table.freeze(_EXP)
```

Once the module ends and the export table is frozen, subsequent reassignments will throw a runtime error, analogous to reassigning keys to a frozen table.

```luau
export counter = 0

export function increment()
-- once the module returns
-- this raises an "attempt to modify a readonly table" error
counter += 1
end

-- desugars into

local _EXP = {}
_EXP.counter = 0

function _EXP.increment()
_EXP.counter += 1
end

return table.freeze(_EXP)
```

### Typechecking
Type inference of exported variables will behave exactly the same as local variable inference.

```luau
-- example behavior subject to change
-- with local variable inference changes

export foo = 15
foo = "hello"
foo = true
-- foo: number | string | boolean

export bar = nil
if math.random(0, 1) == 1 then
bar = 123
end
-- bar: number?
```

This is in contrast to how typechecking would behave in the desugared form with key assignments.

```luau
local _EXP = {}
_EXP.foo = 15
_EXP.foo = "hello" -- type error
_EXP.foo = true -- type error

_EXP.bar = nil
if math.random(0, 1) == 1 then
_EXP.bar = 123 -- type error
end

return table.freeze(_EXP)
```

This is done to ensure exported variables act exactly the same as local variables and preserve the same ergonomics.

### Interaction with `return`

A module that contains an export statement is not permitted to also contain a return statement at the module scope, as the two mechanisms are mutually exclusive. If there is both an export statement and return statement, it is a parse error.

```luau
export a = 1
return {b = 2} -- syntax error
```
```luau
if skip then return end
export a = 1 -- syntax error
```

This restriction does not apply to modules that only contain type exports for backwards compatibility.

### Future Optimizations

While the primary purpose for extending exports is user ergonomics, static exports also open the door for many optimizations that aren't currently possible with dynamic module returns.

For example, exported variables and functions can be transformed into local variables that are stored in VM registers for fast lookup:

```luau
export tau = math.pi * 2
print(tau)

-- becomes
local tau = math.pi * 2
print(tau)
return table.freeze({tau = tau})
```

Furthermore, static exports that are never reassigned to are capable of being inlined and constant folded across modules, assuming future support for static imports.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "staticness" of the export is not required for potential optimizations. Because export statements are top-level statements, we can determine it's final exported value at compile time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess a more correct way to phrase this would be "first-class exports allow for the compiler to assume exported tokens cannot be reassigned after module return, unlocking the ability to bring constant-folding and inlining across module boundaries."


## Drawbacks

This increases compiler complexity in terms of tracking exported tokens and converting them into table assignments.

Since `export` is a contextual keyword, the following statements are valid and might cause confusion. These cases can be solved with current linting and typechecking tools.

```luau
export = 1
export(1)
export "a"
export {x = 1}
```

Similarly, future RFCs such as a theoretical table destructing RFC may run into syntax ambiguities with export declarations, such as below. The first option could still be parsed with lookahead, but the second option would not be possible.

```luau
export {a, b} = t -- looks like export({a, b}) = t
export [a] = t -- looks like export[a] = t
```

Uninitialized exported variables may also cause confusion due to looking like "shorthand exports" that export previously defined variables. For example, the following does not export the function `foo` but instead declares an exported variable that shadows it. This can be solved by implementing a lint that warns about uninitialized exports that are never assigned to.

```luau
local function foo(x) return x * 2 end
export foo -- exports nil, shadows foo
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One additional drawback is, in large Luau files, reassignable exports can introduce a potential footgun. That is the tradeoff to enable cleaner mutual recursion, but I think it should be mentioned at least.

## Alternatives

As always, do nothing and leave users to construct their own module return tables. This would forfeit providing a consistent way for users to expose public APIs and would not allow for future cross-module optimizations.

Permitting exports in `do end` blocks can be scraped, but this would prevent users from scoping exported variables and doesn't make much sense not to support. It is also possible to initially not support this and then add it back in later.

Exported variables could be treated as unassignable after declaration (like `const` variables in JavaScript), but this would make useful patterns such as exporting mutually dependent functions hard to pull off. Furthermore, introducing const-ness to the language would not provide any further optimization opportunities, as the compiler can already determine if a variable is constant if it is never reassigned to.