IppClub / IppClub/YueScript

Silent generation of anonymous functions

Open
#78 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Lua
Stars
613
Forks
45
PR merge metrics
No merged PRs in 30d

Description

I have this function:

export push = ->
	matrix = matrixPool::pop!?::copy(globalTransform) or Matrix.copy(globalTransform)
	transformStack::push(matrix)
	nil

As I'm always paranoid about generating unnecessary garbage, I noticed the memory counter going up when calling this function.

It compiles to:

push = function() -- 48
	local matrix = (function() -- 49
		local _obj_0 = matrixPool:pop() -- 49
		if _obj_0 ~= nil then -- 49
			return _obj_0:copy(globalTransform) -- 49
		end -- 49
		return nil -- 49
	end)() or Matrix.copy(globalTransform) -- 49
	transformStack:push(matrix) -- 51
	return nil -- 52
end -- 48

So the culprit for the garbage is the anonymous function that was generated for this code.

I changed the code to a more conservative form:

export push = ->
	matrix = matrixPool::pop! or Matrix!
	matrix::copy(globalTransform)
	transformStack::push(matrix)
	nil

which compiles to:

push = function() -- 48
	local matrix = matrixPool:pop() or Matrix() -- 49
	matrix:copy(globalTransform) -- 50
	transformStack:push(matrix) -- 51
	return nil -- 52
end -- 48

and the problem went away.

This makes me wary of the existence operator, because I want to write fast code that generates no more garbage than necessary.

I think it would be prudent if there was an option to emit a warning when an abstraction leads to a potentially expensive construction like this. Otherwise it is necessary to proof-read the generated code if you're performance-aware but don't know exactly how an abstraction will be compiled.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the existence-operator example and compare its MoonScript input with the generated Lua shown in the issue. Trace where this expression is compiled and determine how a warning option should expose potentially expensive anonymous-function generation. Done means the option warns for this case without incorrectly warning on the conservative rewrite.

Written by the indexing model from the issue text.

Assessment

Tech stack
lua
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.