|
| 1 | +local utils = require "luacheck.utils" |
| 2 | + |
| 3 | +local stage = {} |
| 4 | + |
| 5 | +local function useless_computed_key_message_format() |
| 6 | + return "It's unnecessary to use computed properties with literals such as {name!}" |
| 7 | +end |
| 8 | + |
| 9 | +stage.warnings = { |
| 10 | + ["701"] = {message_format = useless_computed_key_message_format, |
| 11 | + fields = {"name"}} |
| 12 | +} |
| 13 | + |
| 14 | +local function warn_useless_computed_key(chstate, node, symbol) |
| 15 | + chstate:warn_range("701", node, { |
| 16 | + name = symbol, |
| 17 | + }) |
| 18 | +end |
| 19 | + |
| 20 | +local keywords = utils.array_to_set({ |
| 21 | + "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", |
| 22 | + "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"}) |
| 23 | + |
| 24 | +local function check_computed_key(chstate, key_node) |
| 25 | + if key_node.tag == "String" then |
| 26 | + local symbol = key_node[1] |
| 27 | + if (key_node.end_offset - key_node.offset + 1) > #symbol then |
| 28 | + if string.gmatch(symbol, "[%a_][%a%w_]*$")() == symbol and not keywords[symbol] then |
| 29 | + warn_useless_computed_key(chstate, key_node, symbol) |
| 30 | + end |
| 31 | + end |
| 32 | + end |
| 33 | +end |
| 34 | + |
| 35 | +local function check_nodes(chstate, nodes) |
| 36 | + for _, node in ipairs(nodes) do |
| 37 | + if type(node) == "table" then |
| 38 | + if node.tag == "Pair" then |
| 39 | + local key_node = node[1] |
| 40 | + check_computed_key(chstate, key_node) |
| 41 | + elseif node.tag == "Index" then |
| 42 | + local key_node = node[2] |
| 43 | + check_computed_key(chstate, key_node) |
| 44 | + end |
| 45 | + |
| 46 | + check_nodes(chstate, node) |
| 47 | + end |
| 48 | + end |
| 49 | +end |
| 50 | + |
| 51 | +function stage.run(chstate) |
| 52 | + check_nodes(chstate, chstate.ast) |
| 53 | +end |
| 54 | + |
| 55 | +return stage |
0 commit comments