Skip to content

Commit 261065f

Browse files
authored
fix(static-msg): do not report constants defined in another file (#93)
1 parent fb7a246 commit 261065f

File tree

3 files changed

+13
-4
lines changed

3 files changed

+13
-4
lines changed

sloglint.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ func visit(pass *analysis.Pass, opts *Options, node ast.Node, stack []ast.Node)
252252
msgPos := funcInfo.argsPos - 1
253253

254254
// NOTE: "With" functions have no message argument and must be skipped.
255-
if opts.StaticMsg && msgPos >= 0 && !isStaticMsg(call.Args[msgPos]) {
255+
if opts.StaticMsg && msgPos >= 0 && !isStaticMsg(pass.TypesInfo, call.Args[msgPos]) {
256256
pass.Reportf(call.Args[msgPos].Pos(), "message should be a string literal or a constant")
257257
}
258258

@@ -440,17 +440,18 @@ func isContextInScope(info *types.Info, stack []ast.Node) bool {
440440
return false
441441
}
442442

443-
func isStaticMsg(msg ast.Expr) bool {
443+
func isStaticMsg(info *types.Info, msg ast.Expr) bool {
444444
switch msg := msg.(type) {
445445
case *ast.BasicLit: // e.g. slog.Info("msg")
446446
return msg.Kind == token.STRING
447447
case *ast.Ident: // e.g. const msg = "msg"; slog.Info(msg)
448-
return msg.Obj != nil && msg.Obj.Kind == ast.Con
448+
_, isConst := info.ObjectOf(msg).(*types.Const)
449+
return isConst
449450
case *ast.BinaryExpr: // e.g. slog.Info("x" + "y")
450451
if msg.Op != token.ADD {
451452
panic("unreachable") // only + can be applied to strings.
452453
}
453-
return isStaticMsg(msg.X) && isStaticMsg(msg.Y)
454+
return isStaticMsg(info, msg.X) && isStaticMsg(info, msg.Y)
454455
default:
455456
return false
456457
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
package static_msg
2+
3+
const anotherConstMsg = "msg"

testdata/src/static_msg/static_msg.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,8 @@ func tests() {
4141
slog.Info("msg" + fmt.Sprintf("msg")) // want `message should be a string literal or a constant`
4242
slog.Info("msg" + constMsg + varMsg + fmt.Sprintf("msg")) // want `message should be a string literal or a constant`
4343
}
44+
45+
func issue92() {
46+
slog.Info(constMsg)
47+
slog.Info(anotherConstMsg)
48+
}

0 commit comments

Comments
 (0)