linter

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2022 License: MIT Imports: 53 Imported by: 2

Documentation

Index

Constants

View Source
const (
	// FlagReturn shows whether or not block has "return"
	FlagReturn = 1 << iota
	FlagBreak
	FlagContinue
	FlagThrow
	FlagDie
)
View Source
const (
	LevelError    = lintapi.LevelError
	LevelWarning  = lintapi.LevelWarning
	LevelNotice   = lintapi.LevelNotice
	LevelSecurity = lintapi.LevelSecurity // Like warning, but reported without a context line
)
View Source
const (
	// IgnoreLinterMessage is a commit message that you specify if you want to cancel linter checks for this changeset
	IgnoreLinterMessage = "@linter disable"
)

Variables

This section is empty.

Functions

func FlagsToString

func FlagsToString(f int) string

FlagsToString is designed for debugging flags.

func MemoryLimiterThread

func MemoryLimiterThread(maxFileSize int)

MemoryLimiterThread starts memory limiter goroutine that disallows to use parse files more than maxFileSize total bytes.

Types

type BlockChecker

type BlockChecker interface {
	BeforeEnterNode(ir.Node)
	AfterEnterNode(ir.Node)
	BeforeLeaveNode(ir.Node)
	AfterLeaveNode(ir.Node)
}

BlockChecker is a custom linter that is called on block level

type BlockCheckerCreateFunc

type BlockCheckerCreateFunc func(*BlockContext) BlockChecker

BlockCheckerCreateFunc is a factory function for BlockChecker

type BlockCheckerDefaults

type BlockCheckerDefaults struct{}

BlockCheckerDefaults is a type for embedding into checkers to get default (empty) BlockChecker implementations.

You can "override" any required methods while ignoring the others.

The benefit is higher backwards-compatibility. If new methods are added to BlockChecker, you wouldn't need to change your code right away (especially if you don't need a new hook).

func (BlockCheckerDefaults) AfterEnterNode

func (BlockCheckerDefaults) AfterEnterNode(ir.Node)

func (BlockCheckerDefaults) AfterLeaveNode

func (BlockCheckerDefaults) AfterLeaveNode(ir.Node)

func (BlockCheckerDefaults) BeforeEnterNode

func (BlockCheckerDefaults) BeforeEnterNode(ir.Node)

func (BlockCheckerDefaults) BeforeLeaveNode

func (BlockCheckerDefaults) BeforeLeaveNode(ir.Node)

type BlockContext

type BlockContext struct {
	// contains filtered or unexported fields
}

BlockContext is the context for block checker.

func (*BlockContext) AddQuickfix added in v0.3.0

func (ctx *BlockContext) AddQuickfix(checkName string, fix quickfix.TextEdit)

AddQuickfix adds a new quick fix.

func (*BlockContext) ClassParseState

func (ctx *BlockContext) ClassParseState() *meta.ClassParseState

ClassParseState returns class parse state (namespace, class, etc).

func (*BlockContext) ExprType added in v0.3.0

func (ctx *BlockContext) ExprType(e ir.Node) types.Map

ExprType resolves the type of e expression node.

func (*BlockContext) File added in v0.3.0

func (ctx *BlockContext) File() *workspace.File

File returns the file being analyzed.

func (*BlockContext) Filename

func (ctx *BlockContext) Filename() string

Filename returns the file name of the file being analyzed.

func (*BlockContext) IsRootLevel

func (ctx *BlockContext) IsRootLevel() bool

IsRootLevel reports whether we are analysing root-level code currently.

func (*BlockContext) IsStatement

func (ctx *BlockContext) IsStatement(n ir.Node) bool

IsStatement reports whether or not specified node is a statement.

func (*BlockContext) NodePath added in v0.3.0

func (ctx *BlockContext) NodePath() irutil.NodePath

NodePath returns a node path up to the current traversal position. The path includes the node that is being traversed as well.

func (*BlockContext) PrematureExitFlags

func (ctx *BlockContext) PrematureExitFlags() int

func (*BlockContext) Report

func (ctx *BlockContext) Report(n ir.Node, level int, checkName, msg string, args ...interface{})

Report records linter warning of specified level. chechName is a key that identifies the "checker" (diagnostic name) that found issue being reported.

func (*BlockContext) ReportLocation added in v0.4.0

func (ctx *BlockContext) ReportLocation(location ir.Location, level int, checkName, msg string, args ...interface{})

ReportLocation records linter warning in specified location of specified level. checkName is a key that identifies the "checker" (diagnostic name) that found issue being reported.

func (*BlockContext) ReportPHPDoc added in v0.4.0

func (ctx *BlockContext) ReportPHPDoc(phpDocLocation PHPDocLocation, level int, checkName, msg string, args ...interface{})

ReportPHPDoc records linter warning in PHPDoc of specified level. checkName is a key that identifies the "checker" (diagnostic name) that found issue being reported.

func (*BlockContext) RootState

func (ctx *BlockContext) RootState() map[string]interface{}

RootState returns state from root context.

func (*BlockContext) Scope

func (ctx *BlockContext) Scope() *meta.Scope

Scope returns variables declared in this block.

type CheckerInfo added in v0.4.0

type CheckerInfo struct {
	// Name is a diagnostic short name.
	// If several words are needed, prefer camelCase.
	Name string

	// Default controls whether diagnostic is
	// enabled by default or it should be included by allow-checks explicitly.
	Default bool

	// Quickfix tells whether this checker can automatically fix the reported
	// issues when linter works in -fix mode.
	Quickfix bool

	// Comment is a short summary of what this diagnostic does.
	// A single descriptive sentence is a perfect format for it.
	Comment string

	// Before is a non-compliant code example (before the fix).
	// Optional, but if present, After should also be non-empty.
	Before string

	// After is a compliant code example (after the fix).
	// Optional, but if present, Before should also be non-empty.
	After string

	// Extends tells the check is created by a dynamic rule that
	// extends the internal linter rule.
	Extends bool
}

CheckerInfo provides a single checker (diagnostic) metadata.

This structure may change with different revisions of noverify and get new fields that may be used by the linter.

type CheckersFilter added in v0.4.0

type CheckersFilter struct {
	All []CheckerInfo

	EnableAll bool
	Allowed   map[string]bool
	Excluded  map[string]bool
	Critical  map[string]bool

	ExcludeFileRegexp *regexp.Regexp
}

func NewCheckersFilter added in v0.4.0

func NewCheckersFilter() *CheckersFilter

func NewCheckersFilterWithEnabledAll added in v0.4.0

func NewCheckersFilterWithEnabledAll() *CheckersFilter

func (*CheckersFilter) IsCriticalReport added in v0.4.0

func (c *CheckersFilter) IsCriticalReport(r *Report) bool

func (*CheckersFilter) IsEnabledCheck added in v0.4.0

func (c *CheckersFilter) IsEnabledCheck(checkName string) bool

func (*CheckersFilter) IsEnabledReport added in v0.4.0

func (c *CheckersFilter) IsEnabledReport(checkName, fileName string) bool

type CheckersRegistry added in v0.4.0

type CheckersRegistry struct {
	// contains filtered or unexported fields
}

func (*CheckersRegistry) AddBlockChecker added in v0.4.0

func (reg *CheckersRegistry) AddBlockChecker(c BlockCheckerCreateFunc)

AddBlockChecker registers a custom block linter that will be used on block level.

func (*CheckersRegistry) AddRootChecker added in v0.4.0

func (reg *CheckersRegistry) AddRootChecker(c RootCheckerCreateFunc)

AddRootChecker registers a custom root linter that will be used on root level.

Root checker indexing phase is expected to be stateless. If indexing results need to be saved (and cached), use RegisterRootCheckerWithCacher.

func (*CheckersRegistry) AddRootCheckerWithCacher added in v0.4.0

func (reg *CheckersRegistry) AddRootCheckerWithCacher(cacher MetaCacher, c RootCheckerCreateFunc)

AddRootCheckerWithCacher registers a custom root linter that will be used on root level. Specified cacher is used to save (and load) indexing phase results.

func (*CheckersRegistry) Autofixable added in v0.5.2

func (reg *CheckersRegistry) Autofixable(name string) bool

Autofixable checks if the passed checker is autofixable.

func (*CheckersRegistry) Contains added in v0.4.0

func (reg *CheckersRegistry) Contains(name string) bool

Contains checks the presence of a checker with the given name.

func (*CheckersRegistry) DeclareChecker added in v0.4.0

func (reg *CheckersRegistry) DeclareChecker(info CheckerInfo)

DeclareChecker declares a checker described by an info. It's a good practice to declare *all* provided checks.

If checker is not declared, for example, there is no way to make it enabled by default.

func (*CheckersRegistry) DeclareRules added in v0.4.0

func (reg *CheckersRegistry) DeclareRules(rset *rules.Set)

func (*CheckersRegistry) ListDeclared added in v0.4.0

func (reg *CheckersRegistry) ListDeclared() []CheckerInfo

ListDeclared returns a list of all checkers that were declared. Slice is sorted by checker names.

type Config added in v0.4.0

type Config struct {
	// BaselineProfile is a suppression database for warnings.
	// Nil profile is an empty suppression profile.
	BaselineProfile       *baseline.Profile
	ComputeBaselineHashes bool // Whether we need to compute report hashes
	ConservativeBaseline  bool

	ApplyQuickFixes bool

	// KPHP tells whether we're working in KPHP-compatible mode.
	KPHP bool

	CacheDir string

	// TypoFixer is a rule set for English typos correction.
	// If nil, no misspell checking is performed.
	// See github.com/client9/misspell for details.
	TypoFixer *misspell.Replacer

	// SrcInput implements source code reading from files and buffers.
	SrcInput inputs.SourceInput

	// Rules is a set of dynamically loaded linter diagnostics.
	Rules *rules.Set

	StubsDir string
	Debug    bool

	// MaxConcurrency limits the linter concurrency.
	MaxConcurrency int

	// DebugParseDuration specifies the minimum parse duration for it to be printed to debug output.
	DebugParseDuration time.Duration

	CheckAutoGenerated bool

	IsDiscardVar func(varname string) bool

	ExcludeRegex *regexp.Regexp

	AllowDisable *regexp.Regexp

	PhpExtensions []string

	Checkers *CheckersRegistry

	IgnoreTriggerError bool

	PhpVersion *version.Version

	StrictMixed bool
}

func NewConfig added in v0.4.0

func NewConfig(ver string) *Config

type Linter added in v0.4.0

type Linter struct {
	// contains filtered or unexported fields
}

func NewLinter added in v0.4.0

func NewLinter(config *Config) *Linter

func NewLinterWithInfo added in v0.4.0

func NewLinterWithInfo(config *Config, info *meta.Info) *Linter

func (*Linter) AnalyzeFiles added in v0.4.0

func (l *Linter) AnalyzeFiles(readFileNamesFunc workspace.ReadCallback) []*Report

AnalyzeFiles runs linter on the files that are provided by the readFileNamesFunc function.

func (*Linter) Config added in v0.4.0

func (l *Linter) Config() *Config

func (*Linter) InitStubs added in v0.4.0

func (l *Linter) InitStubs(readFileNamesFunc workspace.ReadCallback)

func (*Linter) InitStubsFromDir added in v0.4.0

func (l *Linter) InitStubsFromDir(dir string)

InitStubsFromDir parses directory with PHPStorm stubs which has all internal PHP classes and functions declared.

func (*Linter) MetaInfo added in v0.4.0

func (l *Linter) MetaInfo() *meta.Info

func (*Linter) NewIndexingWorker added in v0.4.0

func (l *Linter) NewIndexingWorker(id int) *Worker

func (*Linter) NewLintingWorker added in v0.4.0

func (l *Linter) NewLintingWorker(id int) *Worker

func (*Linter) UseCheckersFilter added in v0.4.0

func (l *Linter) UseCheckersFilter(checks *CheckersFilter)

type MetaCacher

type MetaCacher interface {
	// Version returns a unique cache version identifier.
	// When underlying cache structure is updated, version
	// should return different value.
	//
	// Preferably something unique, prefixed with a vendor
	// name, like `mylints-1.0.0` or `extension-abc4`.
	//
	// Returned value is written before Encode() is called to
	// the same writer. It's also read from the reader before
	// Decode() is invoked.
	Version() string

	// Encode stores custom meta cache part data into provided writer.
	// RootChecker is expected to carry the necessary indexing phase results.
	Encode(io.Writer, RootChecker) error

	// Decode loads custom meta cache part data from provided reader.
	// Those results are used insted of running the associated indexer.
	Decode(r io.Reader, filename string) error
}

MetaCacher is an interface for integrating checker-specific indexing results into NoVerify cache.

Usually, every vendor contains a global meta object that can implement MetaCacher and be associated with a relevant root checker.

type PHPDocError added in v0.4.0

type PHPDocError struct {
	Location PHPDocLocation
	Message  string
}

type PHPDocErrors added in v0.4.0

type PHPDocErrors struct {
	// contains filtered or unexported fields
}

type PHPDocLocation added in v0.4.0

type PHPDocLocation struct {
	Node      ir.Node
	Line      int
	Field     int
	WholeLine bool
	// RelativeLine is set if the line number is relative to the
	// given node; otherwise, the line number is considered to be
	// absolute and can be used directly.
	RelativeLine bool
}

func PHPDocAbsoluteLine added in v0.4.0

func PHPDocAbsoluteLine(line int) PHPDocLocation

func PHPDocAbsoluteLineField added in v0.4.0

func PHPDocAbsoluteLineField(line int, field int) PHPDocLocation

func PHPDocLine added in v0.4.0

func PHPDocLine(n ir.Node, line int) PHPDocLocation

func PHPDocLineField added in v0.4.0

func PHPDocLineField(n ir.Node, line int, field int) PHPDocLocation

type ParseResult added in v0.4.0

type ParseResult struct {
	RootNode *ir.Root
	Reports  []*Report
	// contains filtered or unexported fields
}

type QuickFixGenerator added in v0.5.0

type QuickFixGenerator struct {
	// contains filtered or unexported fields
}

func NewQuickFixGenerator added in v0.5.0

func NewQuickFixGenerator(file *workspace.File) *QuickFixGenerator

func (*QuickFixGenerator) Array added in v0.5.0

func (*QuickFixGenerator) NullForNotNullableProperty added in v0.5.0

func (g *QuickFixGenerator) NullForNotNullableProperty(prop *ir.PropertyStmt) quickfix.TextEdit

type Report

type Report struct {
	CheckName string `json:"check_name"`
	Level     int    `json:"level"`
	Context   string `json:"context"`
	Message   string `json:"message"`
	Filename  string `json:"filename"`
	Line      int    `json:"line"`
	StartChar int    `json:"start_char"`
	EndChar   int    `json:"end_char"`
	Hash      uint64 `json:"hash"`
}

Report is a linter report message.

func DiffReports

func DiffReports(gitRepo string, diffArgs []string, changesList []git.Change, changeLog []git.Commit, oldList, newList []*Report, maxConcurrency int) (res []*Report, err error)

DiffReports returns only reports that are new. Pass diffArgs=nil if we are called from diff in working copy.

func (*Report) IsCritical

func (r *Report) IsCritical() bool

IsCritical returns whether or not we need to reject whole commit when found this kind of report.

func (*Report) Severity added in v0.3.0

func (r *Report) Severity() string

type RootChecker

type RootChecker interface {
	BeforeEnterFile()
	AfterLeaveFile()
	BeforeEnterNode(ir.Node)
	AfterEnterNode(ir.Node)
	BeforeLeaveNode(ir.Node)
	AfterLeaveNode(ir.Node)
}

RootChecker is a custom linter that should operator only at root level. Block level analysis (function and method bodies and all if/else/for/etc blocks) must be performed in BlockChecker.

type RootCheckerCreateFunc

type RootCheckerCreateFunc func(*RootContext) RootChecker

RootCheckerCreateFunc is a factory function for RootChecker

type RootCheckerDefaults

type RootCheckerDefaults struct{}

RootCheckerDefaults is a type for embedding into checkers to get default (empty) RootChecker implementations.

You can "override" any required methods while ignoring the others.

The benefit is higher backwards-compatibility. If new methods are added to RootChecker, you wouldn't need to change your code right away (especially if you don't need a new hook).

func (RootCheckerDefaults) AfterEnterNode

func (RootCheckerDefaults) AfterEnterNode(ir.Node)

func (RootCheckerDefaults) AfterLeaveFile

func (RootCheckerDefaults) AfterLeaveFile()

func (RootCheckerDefaults) AfterLeaveNode

func (RootCheckerDefaults) AfterLeaveNode(ir.Node)

func (RootCheckerDefaults) BeforeEnterFile added in v0.3.0

func (RootCheckerDefaults) BeforeEnterFile()

func (RootCheckerDefaults) BeforeEnterNode

func (RootCheckerDefaults) BeforeEnterNode(ir.Node)

func (RootCheckerDefaults) BeforeLeaveNode

func (RootCheckerDefaults) BeforeLeaveNode(ir.Node)

type RootContext

type RootContext struct {
	// contains filtered or unexported fields
}

RootContext is the context for root checker to run on.

func (*RootContext) ClassParseState

func (ctx *RootContext) ClassParseState() *meta.ClassParseState

ClassParseState returns class parse state (namespace, class, etc).

func (*RootContext) File added in v0.3.0

func (ctx *RootContext) File() *workspace.File

File returns analyzed file.

Experimental API.

func (*RootContext) Filename

func (ctx *RootContext) Filename() string

Filename returns the file name of the file being analyzed.

func (*RootContext) ParsePHPDoc added in v0.3.0

func (ctx *RootContext) ParsePHPDoc(doc string) phpdoc.Comment

ParsePHPDoc returns parsed phpdoc comment parts.

func (*RootContext) Report

func (ctx *RootContext) Report(n ir.Node, level int, checkName, msg string, args ...interface{})

Report records linter warning of specified level. checkName is a key that identifies the "checker" (diagnostic name) that found issue being reported.

func (*RootContext) ReportLocation added in v0.4.0

func (ctx *RootContext) ReportLocation(location ir.Location, level int, checkName, msg string, args ...interface{})

ReportLocation records linter warning in specified location of specified level. checkName is a key that identifies the "checker" (diagnostic name) that found issue being reported.

func (*RootContext) ReportPHPDoc added in v0.4.0

func (ctx *RootContext) ReportPHPDoc(phpDocLocation PHPDocLocation, level int, checkName, msg string, args ...interface{})

ReportPHPDoc records linter warning in PHPDoc of specified level. checkName is a key that identifies the "checker" (diagnostic name) that found issue being reported.

func (*RootContext) Scope

func (ctx *RootContext) Scope() *meta.Scope

Scope returns variables declared at root level.

func (*RootContext) State

func (ctx *RootContext) State() map[string]interface{}

State returns state that can be modified and passed into block context

type Worker added in v0.3.0

type Worker struct {
	AllowDisable *regexp.Regexp
	// contains filtered or unexported fields
}

Worker is a linter handle that is expected to be executed in a single goroutine context.

It's not thread-safe and contains the state that will be re-used between the linter API calls.

See NewLintingWorker and NewIndexingWorker.

func (*Worker) ID added in v0.3.0

func (w *Worker) ID() int

func (*Worker) IndexFile added in v0.3.0

func (w *Worker) IndexFile(file workspace.FileInfo) error

IndexFile parses the file and fills in the meta info. Can use cache.

func (*Worker) MetaInfo added in v0.4.0

func (w *Worker) MetaInfo() *meta.Info

func (*Worker) ParseContents added in v0.3.0

func (w *Worker) ParseContents(fileInfo workspace.FileInfo) (result ParseResult, err error)

ParseContents parses specified contents (or file) and returns *RootWalker. Function does not update global meta.

type WorkerContext added in v0.3.0

type WorkerContext struct {
	// contains filtered or unexported fields
}

WorkerContext is a state that is shared between all worker-owned RootWalker's and BlockWalker's.

A worker is a separate goroutine that processed the incoming files.

Since workerContext is worker-bound, that state is never accessed from different threads, so we can re-use it without synchronization.

func NewWorkerContext added in v0.3.0

func NewWorkerContext() *WorkerContext

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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