goxlint

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 8 Imported by: 0

README

goxlint

goxlint is an engine to build your own Go linter.

Status: v0.0.2, early release. The API of the goxlint, cli, and goxlinttest packages can change in each release before v1.0.0. Read the release notes before you update.

goxlint was named goose-lint in v0.0.1. Change imports from github.com/egoisutolabs/goose-lint to github.com/egoisutolabs/goxlint.

You write rules in Go. goxlint loads the code, runs your rules, and shows the results. goxlint also gives configuration, automatic fixes, suppression comments, and a test harness for rules. You do not write this infrastructure yourself.

The rule API is similar to the oxlint and ESLint rule API. A rule registers a function for each AST node type that it examines. When the rule finds a problem, it calls ctx.Report.

var NoFoo = &goxlint.Rule{
	Meta: goxlint.Meta{
		Name:     "no-foo",
		Category: goxlint.Suspicious,
		Messages: map[string]string{"foo": "Do not use `{{name}}`."},
	},
	Create: func(ctx *goxlint.Context) goxlint.Visitor {
		return goxlint.Visit(
			goxlint.On(func(id *ast.Ident) {
				if id.Name == "foo" {
					ctx.Report(goxlint.Diagnostic{Node: id, MessageID: "foo", Data: goxlint.Data{"name": id.Name}})
				}
			}),
		)
	},
}

Features

Feature Description
Visitor rules A rule registers handlers for AST node types. All rules share one walk of each file.
Package rules A rule can also examine all files of a package together.
Type information A rule can request go/types data. goxlint loads types only when a rule needs them.
Configuration A .goxlintrc.json file sets severities, rule options, ignore patterns, and per-file overrides.
Fixes A rule can attach a fix. Fixes have three levels: safe, suggestion, and dangerous.
Suppressions //goxlint:ignore comments disable a rule for a line or a file. goxlint reports unused suppressions.
Output Code frames for people. Also unix, json, and github formats for tools and CI.
Rule tests The goxlinttest package tests a rule with valid and invalid code samples.

Quick start

goxlint is a library. You make a small main package that registers your plugins, and that program is your linter.

  1. Add goxlint to your module:

    go get github.com/egoisutolabs/goxlint
    
  2. Make a plugin and the command:

    // tools/lint/main.go
    package main
    
    import (
    	"github.com/egoisutolabs/goxlint/cli"
    	"github.com/egoisutolabs/goxlint"
    )
    
    var Plugin = goxlint.Plugin{Name: "acme", Rules: []*goxlint.Rule{NoFoo}}
    
    func main() { cli.Main(Plugin) }
    
  3. Run your linter:

    go run ./tools/lint ./...
    

For the full procedure, read Getting started.

Example linter

The examples/goxlint directory has a complete linter that is built with goxlint. It has two example plugins. Use them as a reference when you write your own rules.

go run ./examples/goxlint rules
go run ./examples/goxlint ./...

Documentation

Document Contents
Getting started Make a linter, write a rule, and run it.
Command line Commands, flags, output formats, and exit codes.
Configuration The .goxlintrc.json file.
Writing rules The rule API: metadata, visitors, the context, and reports.
Package rules Rules that examine all files of a package.
Fixes Fix levels and how goxlint applies fixes.
Suppressions //goxlint:ignore comments and unused-suppression reports.
Testing rules The goxlinttest package.
How goxlint works Loading, the walk, the package phase, and the order of operations.

Requirements

  • Go 1.26 or later.

Development

go test -race ./...
go vet ./...

License

goxlint is available under the MIT License.

Documentation

Overview

Package goxlint is the rule-authoring API for goxlint.

A rule declares metadata and a Create function, an AnalyzePackage function, or both. Create runs once per file and returns a Visitor: a set of node handlers that the engine calls during a single shared AST walk. Rules report problems through the Context.

var NoFoo = &goxlint.Rule{
	Meta: goxlint.Meta{
		Name:     "no-foo",
		Category: goxlint.Suspicious,
		Messages: map[string]string{"foo": "Avoid `{{name}}`."},
	},
	Create: func(ctx *goxlint.Context) goxlint.Visitor {
		return goxlint.Visit(
			goxlint.On(func(n *ast.Ident) {
				if n.Name == "foo" {
					ctx.Report(goxlint.Diagnostic{Node: n, MessageID: "foo", Data: goxlint.Data{"name": n.Name}})
				}
			}),
		)
	},
}

Index

Constants

This section is empty.

Variables

Categories lists every category in display order.

Functions

func Interpolate

func Interpolate(tmpl string, data Data) string

Interpolate replaces {{key}} placeholders in tmpl with values from data.

Types

type Category

type Category string

Category groups rules by intent, mirroring oxlint's categories.

const (
	// Correctness rules catch code that is wrong or useless. Enabled by default.
	Correctness Category = "correctness"
	// Suspicious rules catch code that is most likely wrong.
	Suspicious Category = "suspicious"
	// Pedantic rules are strict and may have false positives.
	Pedantic Category = "pedantic"
	// Style rules enforce idiomatic or readable code.
	Style Category = "style"
	// Restriction rules ban patterns that are valid but unwanted by policy.
	Restriction Category = "restriction"
	// Nursery rules are under development.
	Nursery Category = "nursery"
)

type Context

type Context struct {
	// Enabled is false for package-analysis evidence files where the rule is
	// disabled. Reports from those contexts are ignored by the engine.
	Enabled  bool
	Rule     *Rule
	RuleID   string // "<plugin>/<rule>"
	Fset     *token.FileSet
	File     *ast.File
	Filename string
	Source   []byte
	// Pkg and TypesInfo are nil unless the rule's Meta.NeedsTypes is set.
	Pkg       *types.Package
	TypesInfo *types.Info
	// contains filtered or unexported fields
}

Context is a rule's view of the file being linted.

func NewContext

func NewContext(rule *Rule, ruleID string, fset *token.FileSet, file *ast.File, filename string, src []byte,
	pkg *types.Package, info *types.Info, options json.RawMessage, stack *[]ast.Node, report func(Diagnostic)) *Context

NewContext is used by the engine. Rules receive a ready Context from Create.

func (*Context) Ancestors

func (c *Context) Ancestors() []ast.Node

Ancestors returns the ancestors of the current node, nearest first.

func (*Context) CalleeFunc

func (c *Context) CalleeFunc(call *ast.CallExpr) *types.Func

CalleeFunc returns the function or method a call statically invokes, or nil.

func (*Context) CommentsBefore

func (c *Context) CommentsBefore(pos token.Pos) *ast.CommentGroup

CommentsBefore returns the comment group that ends on the line directly above pos, or nil. A blank line between the comment and pos detaches it.

func (*Context) IsPkgFunc

func (c *Context) IsPkgFunc(call *ast.CallExpr, pkgPath string, names ...string) bool

IsPkgFunc reports whether call invokes the package-level function pkgPath.name.

func (*Context) IsTestFile

func (c *Context) IsTestFile() bool

IsTestFile reports whether the file is a _test.go file.

func (*Context) Line

func (c *Context) Line(pos token.Pos) int

Line returns the 1-based line of pos.

func (*Context) ObjectOf

func (c *Context) ObjectOf(id *ast.Ident) types.Object

ObjectOf returns the object id denotes, or nil without type information.

func (*Context) Options

func (c *Context) Options(v any) bool

Options decodes the rule's configured options into v. It leaves v unchanged when no options are configured, so callers set defaults before calling. Invalid options are reported as an error diagnostic and Options returns false; the rule should then return a nil Visitor.

func (*Context) OwnLine

func (c *Context) OwnLine(pos token.Pos) bool

OwnLine reports whether only whitespace precedes pos on its line.

func (*Context) Parent

func (c *Context) Parent() ast.Node

Parent returns the parent of the node currently being visited, or nil at the root.

func (*Context) Report

func (c *Context) Report(d Diagnostic)

Report records a diagnostic. It panics when the rule itself is broken (an unknown message ID, or a fix more dangerous than Meta.Fixable); the engine recovers and reports the rule as failed.

func (*Context) Snippet

func (c *Context) Snippet(node ast.Node) string

Snippet returns node's source collapsed to one line and shortened, for quoting code in messages.

func (*Context) Text

func (c *Context) Text(node ast.Node) string

Text returns the source text of node.

func (*Context) TrailingComment

func (c *Context) TrailingComment(pos token.Pos) *ast.CommentGroup

TrailingComment returns the comment group that starts on the same line as pos, after it, or nil.

func (*Context) TypeOf

func (c *Context) TypeOf(expr ast.Expr) types.Type

TypeOf returns the type of expr, or nil without type information.

type Data

type Data map[string]string

Data supplies values for {{key}} placeholders in message templates.

type Diagnostic

type Diagnostic struct {
	// Node locates the problem. Pos and End may be set instead.
	Node     ast.Node
	Pos, End token.Pos
	// MessageID selects a template from Meta.Messages. Message may be set instead.
	MessageID string
	Message   string
	Data      Data
	// Help is an optional hint printed under the diagnostic.
	Help string
	// Fix is an optional fix. Its kind must not exceed Meta.Fixable.
	Fix *Fix
}

Diagnostic is a problem reported by a rule.

type Edit

type Edit struct {
	Pos, End token.Pos
	NewText  string
}

Edit replaces the source between Pos and End with NewText.

func InsertBefore

func InsertBefore(pos token.Pos, text string) Edit

InsertBefore returns an edit that inserts text at pos.

func ReplaceNode

func ReplaceNode(node ast.Node, text string) Edit

ReplaceNode returns an edit that replaces node with text.

type Fix

type Fix struct {
	Kind    FixKind
	Message string
	Edits   []Edit
}

Fix is a set of non-overlapping text edits.

type FixKind

type FixKind int

FixKind describes how safe a rule's fixes are to apply automatically.

const (
	// FixNone means the rule provides no fixes.
	FixNone FixKind = iota
	// FixSafe fixes never change program behavior. Applied by --fix.
	FixSafe
	// FixSuggestion fixes may change behavior and need review. Applied by --fix-suggestions.
	FixSuggestion
	// FixDangerous fixes can break code. Applied by --fix-dangerously.
	FixDangerous
)

func (FixKind) String

func (k FixKind) String() string

type Handler

type Handler struct {
	NodeType reflect.Type
	Exit     bool
	Fn       func(ast.Node)
}

Handler is a callback for one AST node type, on entry or exit.

func On

func On[N ast.Node](fn func(N)) Handler

On registers fn for every node of type N, called before the node's children.

func OnExit

func OnExit[N ast.Node](fn func(N)) Handler

OnExit registers fn for every node of type N, called after the node's children.

type Meta

type Meta struct {
	// Name is the rule name without the plugin prefix, for example "no-any-parameters".
	Name string
	// Description is a one-line summary shown by `goxlint rules`.
	Description string
	Category    Category
	// Messages maps message IDs to templates. Templates interpolate Data with {{key}}.
	Messages map[string]string
	// Fixable is the most dangerous kind of fix the rule can produce.
	Fixable FixKind
	// NeedsTypes requests type information. When no enabled rule needs types,
	// goxlint parses files directly without loading packages, which is much faster.
	NeedsTypes bool
}

Meta describes a rule.

type PackageContext

type PackageContext struct {
	Name  string
	Files []*Context
}

PackageContext provides the loaded files in one directory and Go package. Files are ordered by filename, include files where this rule is disabled, and exclude ignored and generated files. A partial selection (such as an explicit file pattern in syntax mode) includes only the loaded files. Treat syntax trees and type information as read-only.

type Plugin

type Plugin struct {
	Name  string
	Rules []*Rule
}

Plugin is a named set of rules. Rules are configured as "<plugin>/<rule>".

type Rule

type Rule struct {
	Meta Meta
	// Create runs once per file and returns the handlers to call during the walk.
	// It may be nil for a package-only rule.
	Create func(ctx *Context) Visitor
	// AnalyzePackage runs once per package after file visitors, before suppressions.
	// A rule may provide either or both callbacks. Package state must be local
	// to this invocation: different packages can be analyzed concurrently.
	AnalyzePackage func(ctx *PackageContext)
}

Rule is a lint rule.

type Visitor

type Visitor []Handler

Visitor is the set of node handlers a rule registers for one file.

func Visit

func Visit(handlers ...Handler) Visitor

Visit collects handlers into a Visitor.

Directories

Path Synopsis
Package cli implements the goxlint command.
Package cli implements the goxlint command.
examples
goxlint command
Command goxlint demonstrates a linter built from the goxlint engine and example plugins.
Command goxlint demonstrates a linter built from the goxlint engine and example plugins.
goxlint/plugins/antislop
Package antislop rejects low-evidence and low-signal Go patterns.
Package antislop rejects low-evidence and low-signal Go patterns.
goxlint/plugins/maintainability
Package maintainability provides configurable complexity and duplication checks.
Package maintainability provides configurable complexity and duplication checks.
Package goxlinttest is the RuleTester for goxlint rules.
Package goxlinttest is the RuleTester for goxlint rules.
internal
config
Package config loads .goxlintrc.json and resolves which rules apply to each file.
Package config loads .goxlintrc.json and resolves which rules apply to each file.
engine
Package engine runs goxlint rules over parsed files.
Package engine runs goxlint rules over parsed files.
output
Package output formats diagnostics.
Package output formats diagnostics.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL