Skip to content

Commit

Permalink
Completions: don't suggest loop vars as locals on same line (StyraInc…
Browse files Browse the repository at this point in the history
…#1135)

Fixes StyraInc#1124

Signed-off-by: Anders Eknert <anders@styra.com>
  • Loading branch information
anderseknert authored and srenatus committed Oct 1, 2024
1 parent 4cf2f69 commit 5cc2a2a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
21 changes: 17 additions & 4 deletions bundle/regal/lsp/completion/providers/locals/locals.rego
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@ items contains item if {
word := location.word_at(line, input.regal.context.location.col)
parsed_current_file := data.workspace.parsed[input.regal.file.uri]

some local in location.find_locals(
parsed_current_file.rules,
input.regal.context.location,
)
some local in location.find_locals(parsed_current_file.rules, input.regal.context.location)

startswith(local, word.text)

not local in _same_line_loop_vars(line)

item := {
"label": local,
"kind": kind.variable,
Expand All @@ -49,3 +48,17 @@ _function_args_position(text) if {
contains(text, "(")
not contains(text, "=")
}

default _same_line_loop_vars(_) := []

_same_line_loop_vars(line) := d if {
expr := trim_space(line)

strings.any_prefix_match(expr, {"some", "every"})

# ---------------------------------------------------> "some k, v in coll"
a := substring(expr, 0, indexof(expr, " in")) # -----> "some k, v"
b := trim_prefix(trim_prefix(a, "some"), "every") # -> "k, v"
c := replace(b, " ", "") # --------------------------> "k,v"
d := split(c, ",") # --------------------------------> [k, v] or [v]
}
29 changes: 29 additions & 0 deletions bundle/regal/lsp/completion/providers/locals/locals_test.rego
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package regal.lsp.completion.providers.locals_test

import rego.v1

import data.regal.util

import data.regal.lsp.completion.providers.locals as provider
import data.regal.lsp.completion.providers.test_utils as utils

Expand Down Expand Up @@ -149,6 +151,33 @@ function() if {
count(items) == 0
}

test_no_some_in_vars_suggested_on_same_line if {
workspace := {"file:///p.rego": `package policy
import rego.v1
allow if {
xyz := 1
some xxx, yyy in x
}
`}

regal_module := {"regal": {
"file": {
"name": "p.rego",
"uri": "file:///p.rego",
"lines": split(workspace["file:///p.rego"], "\n"),
},
"context": {"location": {
"row": 7,
"col": 19,
}},
}}
items := provider.items with input as regal_module with data.workspace.parsed as utils.parsed_modules(workspace)

util.single_set_item(items).label == "xyz"
}

_expect_item(items, label, range) if {
expected := {"detail": "local variable", "kind": 6}

Expand Down

0 comments on commit 5cc2a2a

Please sign in to comment.