Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add conditional Suggest #301

Open
tdakkota opened this issue Nov 7, 2021 · 1 comment
Open

Add conditional Suggest #301

tdakkota opened this issue Nov 7, 2021 · 1 comment

Comments

@tdakkota
Copy link

tdakkota commented Nov 7, 2021

Conditional suggesting may be useful to simplify rules and to reduce some matching boilerplate in similar rules.
Also, it makes quickfix specialization very easy.

API

// SuggestIf assigns a quickfix suggestion for the matched code if given cond is satisfied.
func (m Matcher) SuggestIf(cond bool, suggestion string) Matcher {

Example of reducing boilerplate

From

    isSigned := func(v dsl.MatcherVar) bool {
      return v.Type.Is(`int`) || v.Type.Is(`int8`) || v.Type.Is(`int16`) || v.Type.Is(`int32`)  || v.Type.Is(`int64`) 
    }
    m.Match(`fmt.Sprintf("%d", $arg)`, `fmt.Sprintf("%v", $arg)`).
      Where(m["arg"].Type.Is("int64")).
      Suggest(`strconv.FormatInt($arg, 10)`)
    m.Match(`fmt.Sprintf("%d", $arg)`, `fmt.Sprintf("%v", $arg)`).
      Where(m["arg"].Type.Is("int")).
      Suggest(`strconv.Itoa($arg)`)
    m.Match(`fmt.Sprintf("%d", $arg)`, `fmt.Sprintf("%v", $arg)`).
      Where(
          !m["arg"].Type.Is("int") &&
          !m["arg"].Type.Is("int64") &&
          isSigned(m["arg"]) ,
      ).
      Suggest(`strconv.FormatInt(int64($arg), 10)`)

to

        isSigned := func(v dsl.MatcherVar) bool {
           return v.Type.Is(`int`) || v.Type.Is(`int8`) || v.Type.Is(`int16`) || v.Type.Is(`int32`)  || v.Type.Is(`int64`) 
        }
	m.Match(
		`fmt.Sprintf("%d", $arg)`,
		`fmt.Sprintf("%v", $arg)`,
	).Where(isSigned(m["arg"])).
		// Suggest Itoa if arg has 'int' type
		SuggestIf(m["arg"].Type.Is("int"), `strconv.Itoa`).
		// Suggest FormatInt without casting if arg has 'int64' type
		SuggestIf(m["arg"].Type.Is("int64"), `strconv.FormatInt($arg, 10)`).
		// Otherwise, suggest FormatInt with cast
		Suggest(`strconv.FormatInt(int64($arg), 10)`)
@quasilyte
Copy link
Owner

I'll experiment with #302 and we can see whether it helps here or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants