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

simplify slice expr (avoid len) #10

Merged
merged 5 commits into from
Jul 19, 2024
Merged

simplify slice expr (avoid len) #10

merged 5 commits into from
Jul 19, 2024

Conversation

notJoon
Copy link
Contributor

@notJoon notJoon commented Jul 19, 2024

Simplify expression when specifying lengths with the len function inside a slice.

Handling these cases:

slice[:len(slice)] → slice[:]
slice[n:len(slice)] → slice[n:] // n: number literal
slice[a:len(slice)] → slice[a:] // a: variable

Example

package slice

var slice = []int{1, 2, 3}

func foo() {
	_ = slice[1:len(slice)]
}

func bar() {
	_ = slice[:len(slice)]
}

func baz() {
	a := 1
	_ = slice[a:len(slice)]
}

Linter result:

error: simplify-slice-range
 --> testdata/slice0.gno
  |
6 |         _ = slice[1:len(slice)]
  |      ^ unnecessary use of len() in slice expression, can be simplified

Suggestion:
6 | slice[1:]

Note: unnecessary use of len() in slice expression, can be simplified
Here, `slice[1:len(slice)]` can be simplified to `slice[1:]`. When slicing to the end of a slice, using len() is unnecessary.

error: simplify-slice-range
 --> testdata/slice0.gno
   |
10 |         _ = slice[:len(slice)]
   |      ^ unnecessary use of len() in slice expression, can be simplified

Suggestion:
10 | slice[:]

Note: unnecessary use of len() in slice expression, can be simplified
In this case, `slice[:len(slice)]` is equivalent to `slice[:]`. The full length of the slice is already implied when omitting both start and end indices.

error: simplify-slice-range
 --> testdata/slice0.gno
   |
15 |         _ = slice[a:len(slice)]
   |      ^ unnecessary use of len() in slice expression, can be simplified

Suggestion:
15 | slice[a:]

Note: unnecessary use of len() in slice expression, can be simplified
In this instance, `slice[a:len(slice)]` can be written as `slice[a:]`. The len() function is redundant when slicing to the end, regardless of the start index.

@notJoon notJoon marked this pull request as ready for review July 19, 2024 05:24
@notJoon notJoon merged commit 32a28a8 into main Jul 19, 2024
1 check passed
@notJoon notJoon deleted the rule-slice-length branch July 19, 2024 05:29
@notJoon notJoon added the A-lint Adding or updating lint label Jul 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Adding or updating lint
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant