summaryrefslogtreecommitdiff
path: root/script/core/rename.lua
blob: 0851f1910f4ff1c03d9a5ee8643e0f782d06d342 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
local files      = require 'files'
local vm         = require 'vm'
local searcher   = require 'core.searcher'
local proto      = require 'proto'
local define     = require 'proto.define'
local util       = require 'utility'
local findSource = require 'core.find-source'
local ws         = require 'workspace'

local Forcing

local function askForcing(str)
    -- TODO 总是可以替换
    do return true end
    if TEST then
        return true
    end
    if Forcing ~= nil then
        return Forcing
    end
    local version = files.globalVersion
    -- TODO
    local item = proto.awaitRequest('window/showMessageRequest', {
        type    = define.MessageType.Warning,
        message = ('[%s]不是有效的标识符,是否强制替换?'):format(str),
        actions = {
            {
                title = '强制替换',
            },
            {
                title = '取消',
            },
        }
    })
    if version ~= files.globalVersion then
        Forcing = false
        proto.notify('window/showMessage', {
            type    = define.MessageType.Warning,
            message = '文件发生了变化,替换取消。'
        })
        return false
    end
    if not item then
        Forcing = false
        return false
    end
    if item.title == '强制替换' then
        Forcing = true
        return true
    else
        Forcing = false
        return false
    end
end

local function askForMultiChange(results, newname)
    -- TODO 总是可以替换
    do return true end
    if TEST then
        return true
    end
    local uris = {}
    for _, result in ipairs(results) do
        local uri = result.uri
        if not uris[uri] then
            uris[uri] = 0
            uris[#uris+1] = uri
        end
        uris[uri] = uris[uri] + 1
    end
    if #uris <= 1 then
        return true
    end

    local version = files.globalVersion
    -- TODO
    local item = proto.awaitRequest('window/showMessageRequest', {
        type    = define.MessageType.Warning,
        message = ('将修改 %d 个文件,共 %d 处。'):format(
            #uris,
            #results
        ),
        actions = {
            {
                title = '继续',
            },
            {
                title = '放弃',
            },
        }
    })
    if version ~= files.globalVersion then
        proto.notify('window/showMessage', {
            type    = define.MessageType.Warning,
            message = '文件发生了变化,替换取消。'
        })
        return false
    end
    if item and item.title == '继续' then
        local fileList = {}
        for _, uri in ipairs(uris) do
            fileList[#fileList+1] = ('%s (%d)'):format(uri, uris[uri])
        end

        log.debug(('Renamed [%s]\r\n%s'):format(newname, table.concat(fileList, '\r\n')))
        return true
    end
    return false
end

local function trim(str)
    return str:match '^%s*(%S+)%s*$'
end

local function isValidName(str)
    if not str then
        return false
    end
    return str:match '^[%a_][%w_]*$'
end

local function isValidGlobal(str)
    if not str then
        return false
    end
    for s in str:gmatch '[^%.]*' do
        if not isValidName(trim(s)) then
            return false
        end
    end
    return true
end

local function isValidFunctionName(str)
    if isValidGlobal(str) then
        return true
    end
    local pos = str:find(':', 1, true)
    if not pos then
        return false
    end
    return  isValidGlobal(trim(str:sub(1, pos-1)))
        and isValidName(trim(str:sub(pos+1)))
end

local function isFunctionGlobalName(source)
    local parent = source.parent
    if parent.type ~= 'setglobal' then
        return false
    end
    local value = parent.value
    if not value.type ~= 'function' then
        return false
    end
    return value.start <= parent.start
end

local function renameLocal(source, newname, callback)
    if isValidName(newname) then
        callback(source, source.start, source.finish, newname)
        return
    end
    if askForcing(newname) then
        callback(source, source.start, source.finish, newname)
    end
end

local function renameField(source, newname, callback)
    if isValidName(newname) then
        callback(source, source.start, source.finish, newname)
        return true
    end
    local parent = source.parent
    if parent.type == 'setfield'
    or parent.type == 'getfield' then
        local dot = parent.dot
        local newstr = '[' .. util.viewString(newname) .. ']'
        callback(source, dot.start, source.finish, newstr)
    elseif parent.type == 'tablefield' then
        local newstr = '[' .. util.viewString(newname) .. ']'
        callback(source, source.start, source.finish, newstr)
    elseif parent.type == 'getmethod' then
        if not askForcing(newname) then
            return false
        end
        callback(source, source.start, source.finish, newname)
    elseif parent.type == 'setmethod' then
        local uri = searcher.getUri(source)
        local text = files.getText(uri)
        local func = parent.value
        -- function mt:name () end --> mt['newname'] = function (self) end
        local newstr = string.format('%s[%s] = function '
            , text:sub(parent.start, parent.node.finish)
            , util.viewString(newname)
        )
        callback(source, func.start, parent.finish, newstr)
        local pl = text:find('(', parent.finish, true)
        if pl then
            if text:find('^%s*%)', pl + 1) then
                callback(source, pl + 1, pl, 'self')
            else
                callback(source, pl + 1, pl, 'self, ')
            end
        end
    end
    return true
end

local function renameGlobal(source, newname, callback)
    if isValidGlobal(newname) then
        callback(source, source.start, source.finish, newname)
        return true
    end
    if isValidFunctionName(newname) then
        if not isFunctionGlobalName(source) then
            askForcing(newname)
        end
        callback(source, source.start, source.finish, newname)
        return true
    end
    local newstr = '_ENV[' .. util.viewString(newname) .. ']'
    -- function name () end --> _ENV['newname'] = function () end
    if source.value and source.value.type == 'function'
    and source.value.start < source.start then
        callback(source, source.value.start, source.finish, newstr .. ' = function ')
        return true
    end
    callback(source, source.start, source.finish, newstr)
    return true
end

local function ofLocal(source, newname, callback)
    renameLocal(source, newname, callback)
    if source.ref then
        for _, ref in ipairs(source.ref) do
            renameLocal(ref, newname, callback)
        end
    end
    if  source.parent.type == 'funcargs'
    and source.bindDocs then
        for _, doc in ipairs(source.bindDocs) do
            if doc.type == 'doc.param'
            and doc.param[1] == source[1] then
                callback(doc.param, doc.param.start, doc.param.finish, newname)
            end
        end
    end
end

local function ofFieldThen(key, src, newname, callback)
    if vm.getKeyName(src) ~= key then
        return
    end
    if     src.type == 'tablefield'
    or     src.type == 'getfield'
    or     src.type == 'setfield' then
        src = src.field
    elseif src.type == 'tableindex'
    or     src.type == 'getindex'
    or     src.type == 'setindex' then
        src = src.index
    elseif src.type == 'getmethod'
    or     src.type == 'setmethod' then
        src = src.method
    end
    if src.type == 'string' then
        local quo = src[2]
        local text = util.viewString(newname, quo)
        callback(src, src.start, src.finish, text)
        return
    elseif src.type == 'field'
    or     src.type == 'method' then
        local suc = renameField(src, newname, callback)
        if not suc then
            return
        end
    elseif src.type == 'setglobal'
    or     src.type == 'getglobal' then
        local suc = renameGlobal(src, newname, callback)
        if not suc then
            return
        end
    end
end

local function ofField(source, newname, callback)
    local key = searcher.getKeyName(source)
    local node
    if source.type == 'tablefield'
    or source.type == 'tableindex' then
        node = source.parent
    else
        node = source.node
    end
    for _, src in ipairs(vm.getFields(node, 5)) do
        ofFieldThen(key, src, newname, callback)
    end
end

local function ofGlobal(source, newname, callback)
    local key = searcher.getKeyName(source)
    for _, src in ipairs(vm.getRefs(source, 0)) do
        ofFieldThen(key, src, newname, callback)
    end
end

local function ofLabel(source, newname, callback)
    if not isValidName(newname) and not askForcing(newname)then
        return false
    end
    for _, src in ipairs(vm.getRefs(source, 0)) do
        callback(src, src.start, src.finish, newname)
    end
end

local function ofDocTypeName(source, newname, callback)
    for _, doc in ipairs(vm.getDocTypes(source[1])) do
        if doc.type == 'doc.class.name'
        or doc.type == 'doc.type.name'
        or doc.type == 'doc.alias.name' then
            callback(doc, doc.start, doc.finish, newname)
        end
    end
end

local function ofDocParamName(source, newname, callback)
    callback(source, source.start, source.finish, newname)
    local doc = searcher.getDocState(source)
    if doc.bindSources then
        for _, src in ipairs(doc.bindSources) do
            if src.type == 'local'
            and src.parent.type == 'funcargs'
            and src[1] == source[1] then
                renameLocal(src, newname, callback)
                if src.ref then
                    for _, ref in ipairs(src.ref) do
                        renameLocal(ref, newname, callback)
                    end
                end
            end
        end
    end
end

local function rename(source, newname, callback)
    if source.type == 'label'
    or source.type == 'goto' then
        return ofLabel(source, newname, callback)
    elseif source.type == 'local' then
        return ofLocal(source, newname, callback)
    elseif source.type == 'setlocal'
    or     source.type == 'getlocal' then
        return ofLocal(source.node, newname, callback)
    elseif source.type == 'field'
    or     source.type == 'method'
    or     source.type == 'index' then
        return ofField(source.parent, newname, callback)
    elseif source.type == 'setglobal'
    or     source.type == 'getglobal' then
        return ofGlobal(source, newname, callback)
    elseif source.type == 'doc.class.name'
    or     source.type == 'doc.type.name'
    or     source.type == 'doc.alias.name' then
        return ofDocTypeName(source, newname, callback)
    elseif source.type == 'doc.param.name' then
        return ofDocParamName(source, newname, callback)
    elseif source.type == 'string'
    or     source.type == 'number'
    or     source.type == 'boolean' then
        local parent = source.parent
        if not parent then
            return
        end
        if parent.type == 'setindex'
        or parent.type == 'getindex'
        or parent.type == 'tableindex' then
            return ofField(parent, newname, callback)
        end
    end
    return
end

local function prepareRename(source)
    if source.type == 'label'
    or source.type == 'goto'
    or source.type == 'local'
    or source.type == 'setlocal'
    or source.type == 'getlocal'
    or source.type == 'field'
    or source.type == 'method'
    or source.type == 'tablefield'
    or source.type == 'setglobal'
    or source.type == 'getglobal'
    or source.type == 'doc.class.name'
    or source.type == 'doc.type.name'
    or source.type == 'doc.alias.name'
    or source.type == 'doc.param.name' then
        return source, source[1]
    elseif source.type == 'string'
    or     source.type == 'number'
    or     source.type == 'boolean' then
        local parent = source.parent
        if not parent then
            return nil
        end
        if parent.type == 'setindex'
        or parent.type == 'getindex'
        or parent.type == 'tableindex' then
            return source, source[1]
        end
        return nil
    end
    return nil
end

local accept = {
    ['label']      = true,
    ['goto']       = true,
    ['local']      = true,
    ['setlocal']   = true,
    ['getlocal']   = true,
    ['field']      = true,
    ['method']     = true,
    ['tablefield'] = true,
    ['setglobal']  = true,
    ['getglobal']  = true,
    ['string']     = true,
    ['boolean']    = true,
    ['number']     = true,

    ['doc.class.name'] = true,
    ['doc.type.name']  = true,
    ['doc.alias.name'] = true,
    ['doc.param.name'] = true,
}

local m = {}

function m.rename(uri, pos, newname)
    if not newname then
        return nil
    end
    local ast = files.getAst(uri)
    if not ast then
        return nil
    end
    local source = findSource(ast, pos, accept)
    if not source then
        return nil
    end
    local results = {}
    local mark = {}

    rename(source, newname, function (target, start, finish, text)
        local turi = files.getOriginUri(searcher.getUri(target))
        if not turi then
            return
        end
        local uid = turi .. start
        if mark[uid] then
            return
        end
        mark[uid] = true
        if files.isLibrary(turi) then
            return
        end
        results[#results+1] = {
            start  = start,
            finish = finish,
            text   = text,
            uri    = turi,
        }
    end)

    if Forcing == false then
        Forcing = nil
        return nil
    end

    if #results == 0 then
        return nil
    end

    if not askForMultiChange(results, newname) then
        return nil
    end

    return results
end

function m.prepareRename(uri, pos)
    local ast = files.getAst(uri)
    if not ast then
        return nil
    end
    local source = findSource(ast, pos, accept)
    if not source then
        return
    end

    local res, text = prepareRename(source)
    if not res then
        return nil
    end

    return {
        start  = source.start,
        finish = source.finish,
        text   = text,
    }
end

return m