@@ -4,6 +4,9 @@ local util = require 'utility'
44local sp = require ' bee.subprocess'
55local guide = require " parser.guide"
66local converter = require ' proto.converter'
7+ local autoreq = require ' core.completion.auto-require'
8+ local rpath = require ' workspace.require-path'
9+ local furi = require ' file-uri'
710
811--- @param uri uri
912--- @param row integer
@@ -676,6 +679,66 @@ local function checkJsonToLua(results, uri, start, finish)
676679 }
677680end
678681
682+ local function findRequireTargets (visiblePaths )
683+ local targets = {}
684+ for _ , visible in ipairs (visiblePaths ) do
685+ targets [# targets + 1 ] = visible .name
686+ end
687+ return targets
688+ end
689+
690+ local function checkMissingRequire (results , uri , start , finish , diagnostics )
691+ local state = files .getState (uri )
692+ local text = files .getText (uri )
693+ if not state or not text then
694+ return
695+ end
696+
697+ local potentialGlobals = {}
698+ guide .eachSourceBetween (state .ast , start , finish , function (source )
699+ if source .type == ' getglobal' then
700+ potentialGlobals [# potentialGlobals + 1 ] = { name = source [1 ], endpos = source .finish }
701+ end
702+ end )
703+
704+ local function addPotentialRequires (global )
705+ autoreq .check (state , global .name , global .endpos , function (moduleFile , stemname , targetSource )
706+ local visiblePaths = rpath .getVisiblePath (uri , furi .decode (moduleFile ))
707+ if not visiblePaths or # visiblePaths == 0 then return end
708+
709+ for _ , target in ipairs (findRequireTargets (visiblePaths )) do
710+ results [# results + 1 ] = {
711+ title = lang .script (' ACTION_AUTOREQUIRE' , global .name , target ),
712+ kind = ' refactor.rewrite' ,
713+ command = {
714+ title = ' autoRequire' ,
715+ command = ' lua.autoRequire' ,
716+ arguments = {
717+ {
718+ uri = guide .getUri (state .ast ),
719+ target = moduleFile ,
720+ name = global .name ,
721+ requireName = target
722+ },
723+ },
724+ }
725+ }
726+ end
727+ end )
728+ end
729+
730+ -- TODO: Is there a better way to detect undefined-global?
731+ for _ , diag in ipairs (diagnostics ) do
732+ if diag .code == ' undefined-global' then
733+ for _ , potglobal in ipairs (potentialGlobals ) do
734+ if diag .message :find (potglobal .name ) then
735+ addPotentialRequires (potglobal )
736+ end
737+ end
738+ end
739+ end
740+ end
741+
679742return function (uri , start , finish , diagnostics )
680743 local ast = files .getState (uri )
681744 if not ast then
@@ -688,6 +751,7 @@ return function (uri, start, finish, diagnostics)
688751 checkSwapParams (results , uri , start , finish )
689752 -- checkExtractAsFunction(results, uri, start, finish)
690753 checkJsonToLua (results , uri , start , finish )
754+ checkMissingRequire (results , uri , start , finish , diagnostics )
691755
692756 return results
693757end
0 commit comments