linter

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2020 License: MIT Imports: 51 Imported by: 0

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
	LevelInformation = lintapi.LevelInformation
	LevelHint        = lintapi.LevelHint
	LevelUnused      = lintapi.LevelUnused
	LevelDoNotReject = lintapi.LevelMaybe
	LevelSyntax      = lintapi.LevelSyntax
)
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

View Source
var (
	// LangServer represents whether or not we run in a language server mode.
	LangServer 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

	// AnalysisFiles is a list of files that are being analyzed (in non-git mode)
	AnalysisFiles []string

	// SrcInput implements source code reading from files and buffers.
	//
	// TODO(quasilyte): avoid having it as a global variable?
	SrcInput = inputs.NewDefaultSourceInput()

	// Rules is a set of dynamically loaded linter diagnostics.
	Rules = &rules.Set{}

	// settings
	StubsDir        string
	Debug           bool
	MaxConcurrency  = runtime.NumCPU()
	MaxFileSize     int
	DefaultEncoding string
	PHPExtensions   []string

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

	CheckAutoGenerated bool

	IsDiscardVar = isUnderscore

	ExcludeRegex *regexp.Regexp
)

Functions

func AnalyzeFileRootLevel

func AnalyzeFileRootLevel(rootNode node.Node, d *RootWalker)

AnalyzeFileRootLevel does analyze file top-level code. This method is exposed for language server use, you usually do not need to call it yourself.

func DebugMessage

func DebugMessage(msg string, args ...interface{})

DebugMessage is used to actually print debug messages.

func DeclareCheck

func DeclareCheck(info CheckInfo)

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

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

func FlagsToString

func FlagsToString(f int) string

FlagsToString is designed for debugging flags.

func FmtNode

func FmtNode(n node.Node) string

FmtNode is used for debug purposes and returns string representation of a specified node.

func IndexFile

func IndexFile(filename string, contents []byte) error

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

func InitStubs

func InitStubs()

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

func MemoryLimiterThread

func MemoryLimiterThread()

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

func RegisterBlockChecker

func RegisterBlockChecker(c BlockCheckerCreateFunc)

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

func RegisterRootChecker

func RegisterRootChecker(c RootCheckerCreateFunc)

RegisterRootChecker 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 RegisterRootCheckerWithCacher

func RegisterRootCheckerWithCacher(cacher MetaCacher, c RootCheckerCreateFunc)

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

Types

type BlockChecker

type BlockChecker interface {
	BeforeEnterNode(walker.Walkable)
	AfterEnterNode(walker.Walkable)
	BeforeLeaveNode(walker.Walkable)
	AfterLeaveNode(walker.Walkable)
}

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(walker.Walkable)

func (BlockCheckerDefaults) AfterLeaveNode

func (BlockCheckerDefaults) AfterLeaveNode(walker.Walkable)

func (BlockCheckerDefaults) BeforeEnterNode

func (BlockCheckerDefaults) BeforeEnterNode(walker.Walkable)

func (BlockCheckerDefaults) BeforeLeaveNode

func (BlockCheckerDefaults) BeforeLeaveNode(walker.Walkable)

type BlockContext

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

BlockContext is the context for block checker.

func (*BlockContext) ClassParseState

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

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

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 node.Node) bool

IsStatement reports whether or not specified node is a statement.

func (*BlockContext) PrematureExitFlags

func (ctx *BlockContext) PrematureExitFlags() int

func (*BlockContext) Report

func (ctx *BlockContext) Report(n node.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) 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 BlockWalker

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

BlockWalker is used to process function/method contents.

func (*BlockWalker) EnterNode

func (b *BlockWalker) EnterNode(w walker.Walkable) (res bool)

EnterNode is called before walking to inner nodes.

func (*BlockWalker) LeaveNode

func (b *BlockWalker) LeaveNode(w walker.Walkable)

LeaveNode is called after all children have been visited.

func (*BlockWalker) ReportBitwiseOp

func (b *BlockWalker) ReportBitwiseOp(s node.Node, op string, rightOp string)

type CheckInfo

type CheckInfo 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

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

CheckInfo provides a single check (diagnostic) metadata.

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

func GetDeclaredChecks

func GetDeclaredChecks() []CheckInfo

GetDeclaredChecks returns a list of all checks that were declared. Slice is sorted by check names.

type FileInfo

type FileInfo struct {
	Filename   string
	Contents   []byte
	LineRanges []git.LineRange
}

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 ParseWaiter

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

ParseWaiter waits to allow parsing of a file.

func BeforeParse

func BeforeParse(size int, filename string) *ParseWaiter

BeforeParse must be called before parsing file, so that soft memory limit can be applied. Do not forget to call Finish()!

func (*ParseWaiter) Finish

func (p *ParseWaiter) Finish()

Finish must be called after parsing is finished (e.g. using defer p.Finish()) to allow other goroutines to parse files.

type ReadCallback

type ReadCallback func(ch chan FileInfo)

func ReadChangesFromWorkTree

func ReadChangesFromWorkTree(dir string, changes []git.Change) ReadCallback

ReadChangesFromWorkTree returns callback that reads files from workTree dir that are changed

func ReadFilenames

func ReadFilenames(filenames []string, ignoreRegex *regexp.Regexp) ReadCallback

ReadFilenames returns callback that reads filenames into channel

func ReadFilesFromGit

func ReadFilesFromGit(repo, commitSHA1 string, ignoreRegex *regexp.Regexp) ReadCallback

ReadFilesFromGit parses file contents in the specified commit

func ReadFilesFromGitWithChanges

func ReadFilesFromGitWithChanges(repo, commitSHA1 string, changes []git.Change) ReadCallback

ReadFilesFromGitWithChanges parses file contents in the specified commit, but only specified ranges

func ReadOldFilesFromGit

func ReadOldFilesFromGit(repo, commitSHA1 string, changes []git.Change) ReadCallback

ReadOldFilesFromGit parses file contents in the specified commit, the old version

type Report

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

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 ParseFilenames

func ParseFilenames(readFileNamesFunc ReadCallback) []*Report

ParseFilenames is used to do initial parsing of files.

func (*Report) CheckName

func (r *Report) CheckName() string

CheckName returns report associated check name.

func (*Report) GetFilename

func (r *Report) GetFilename() string

GetFilename returns report filename

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) IsDisabledByUser

func (r *Report) IsDisabledByUser() bool

IsDisabledByUser returns whether or not user thinks that this file should not be checked

func (*Report) MarshalJSON

func (r *Report) MarshalJSON() ([]byte, error)

MarshalJSON is used to write report in its JSON representation.

Used for -output-json option.

func (*Report) String

func (r *Report) String() string

type RootChecker

type RootChecker interface {
	AfterLeaveFile()
	BeforeEnterNode(walker.Walkable)
	AfterEnterNode(walker.Walkable)
	BeforeLeaveNode(walker.Walkable)
	AfterLeaveNode(walker.Walkable)
}

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(walker.Walkable)

func (RootCheckerDefaults) AfterLeaveFile

func (RootCheckerDefaults) AfterLeaveFile()

func (RootCheckerDefaults) AfterLeaveNode

func (RootCheckerDefaults) AfterLeaveNode(walker.Walkable)

func (RootCheckerDefaults) BeforeEnterNode

func (RootCheckerDefaults) BeforeEnterNode(walker.Walkable)

func (RootCheckerDefaults) BeforeLeaveNode

func (RootCheckerDefaults) BeforeLeaveNode(walker.Walkable)

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) FileContents

func (ctx *RootContext) FileContents() []byte

FileContents returns analyzed file source code. Caller should not modify the returned slice.

Experimental API.

func (*RootContext) Filename

func (ctx *RootContext) Filename() string

Filename returns the file name of the file being analyzed.

func (*RootContext) Report

func (ctx *RootContext) Report(n node.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 (*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 RootWalker

type RootWalker struct {

	// state required for both language server and reports creation
	Lines          [][]byte
	LinesPositions []int

	// exposed meta-information for language server to use
	Scopes      map[node.Node]*meta.Scope
	Diagnostics []vscode.Diagnostic
	// contains filtered or unexported fields
}

RootWalker is used to analyze root scope. Mostly defines, function and class definitions are analyzed.

func NewWalkerForLangServer

func NewWalkerForLangServer(prev *RootWalker) *RootWalker

NewWalkerForLangServer creates a copy of RootWalker to make full analysis of a file

func NewWalkerForReferencesSearcher

func NewWalkerForReferencesSearcher(filename string, block BlockCheckerCreateFunc) *RootWalker

NewWalkerForReferencesSearcher allows to access full context of a parser so that we can perform complex searches if needed.

func ParseContents

func ParseContents(filename string, contents []byte, lineRanges []git.LineRange) (rootNode node.Node, w *RootWalker, err error)

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

func (*RootWalker) EnterNode

func (d *RootWalker) EnterNode(w walker.Walkable) (res bool)

EnterNode is invoked at every node in hierarchy

func (*RootWalker) GetReports

func (d *RootWalker) GetReports() []*Report

GetReports returns collected reports for this file.

func (*RootWalker) InitCustom

func (d *RootWalker) InitCustom()

InitCustom is needed to initialize walker state

func (*RootWalker) InitFromParser

func (d *RootWalker) InitFromParser(contents []byte, parser *php7.Parser)

InitFromParser initializes common fields that are needed for RootWalker work

func (*RootWalker) LeaveNode

func (d *RootWalker) LeaveNode(n walker.Walkable)

LeaveNode is invoked after node process

func (*RootWalker) Report

func (d *RootWalker) Report(n node.Node, level int, checkName, msg string, args ...interface{})

Report registers a single report message about some found problem.

func (*RootWalker) UpdateMetaInfo

func (d *RootWalker) UpdateMetaInfo()

UpdateMetaInfo is intended to be used in tests. Do not use it directly!

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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