StyLua icon indicating copy to clipboard operation
StyLua copied to clipboard

Sort requires attempts to sort before the definitions of variables that are referenced within the require

Open christopher-buss opened this issue 7 months ago • 2 comments

Currently we have to have sort-requires off as we override the require global.

The following gets sorted incorrectly:

local require = require(ReplicatedStorage:WaitForChild("Sonar"))
local DisplayUtils = require("DisplayUtils")
local Maid = require("Maid")
local FormatNumber = require("FormatNumber")
local GameUtils = require("GameUtils")
local RemoteUtils = require("RemoteUtils")
local Button = require("Button")
local Button = require("Button")
local DisplayUtils = require("DisplayUtils")
local FormatNumber = require("FormatNumber")
local GameUtils = require("GameUtils")
local Maid = require("Maid")
local RemoteUtils = require("RemoteUtils")
local require = require(ReplicatedStorage:WaitForChild("Sonar"))

I propose the ability to suggest a glob pattern, such as:

[sort_requires]
enabled = true
glob = "require*"

This would then allow us to hoist the require to the top, and continue to sort the rest of our requires lexicographically.

christopher-buss avatar May 10 '25 18:05 christopher-buss

Taking a step back - rather than creating a configuration for glob matching, maybe the correct approach is to have some basic analysis so that sort requires does not move things above the definitions of variables it references? So in this case, since we are referencing the require local variable, at a minimum the sorting must be placed below this variable.

Also I'm not quite sure how the glob example works in your case - doesn't everything still match the glob?

JohnnyMorganz avatar May 11 '25 13:05 JohnnyMorganz

I did think this was probably a better approach, but thought it may be a lot more complicated to implement. I'm happy for a solution like that to exist, but I don't have the Rust knowledge to do it myself.

In this case, only things that are matched by the pattern, in my case, variables beginning with the word "require" are being hoisted to the top, and then the rest are left in order.

christopher-buss avatar May 11 '25 13:05 christopher-buss