Skip to content

Slow rule speed #412

@lcd1232-epam

Description

@lcd1232-epam

Example code:

//doc:summary reports that you create mocks in an old-fashioned way
//doc:before mockReader := &iomocks.Reader{}
//doc:after mockReader := iomocks.NewReader(t)
func mockConstructor(m dsl.Matcher) {
	m.Import("github.com/stretchr/testify/mock")

	m.Match(
		`$x := &$y{}`,
		`$x := $y{}`,
		`$x = &$y{}`,
		`$x = $y{}`,
	).
		Where(
			m["x"].Type.Underlying().Is(`struct{$*_; mock.Mock; $*_}`) ||
				m["x"].Filter(embedsMock),
		).
		Report("Use the mock constructor instead of struct initialization")
}

func embedsMock(ctx *dsl.VarFilterContext) bool {
	// copy from here - https://github.com/quasilyte/go-ruleguard/blob/7968289708448cdc8ea2fa21d0db203a75d93994/analyzer/testdata/src/quasigo/rules.go#L11-L31
	typ := ctx.Type.Underlying()
	asPointer := types.AsPointer(typ)
	if asPointer != nil {
		typ = asPointer.Elem().Underlying()
	}
	asStruct := types.AsStruct(typ)
	if asStruct == nil {
		return false
	}
	mutexType := ctx.GetType(`github.com/stretchr/testify/mock.Mock`)
	i := 0
	for i < asStruct.NumFields() {
		field := asStruct.Field(i)
		if field.Embedded() && types.Identical(field.Type(), mutexType) {
			return true
		}
		i++
	}
	return false
}

Before using this rule: ~7m
After this rule: ~14m

Are there any way to improve it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions