Skip to content

Commit

Permalink
unused variables are ok with leading _ (#124)
Browse files Browse the repository at this point in the history
* test/utils: support RegEx in HeliosTest.fails

* unused vars are ok with leading _, IFF actually not used

* add pre-push hook

* Test current branch if git doesn't provide a list of things to push

* test/utils: support RegEx in HeliosTest.fails (after #128)

* unused vars are ok with leading _, IFF actually not used

---------

Co-authored-by: Randall <[email protected]>
  • Loading branch information
rjharmon and Randall authored Sep 30, 2024
1 parent 926c020 commit 9a140ae
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/scopes/Scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,20 +218,27 @@ export class Scope extends Common {
}

/**
* Asserts that all named values are user.
* Throws an error if some are unused.
* Asserts that all named values are used.
* Throws an error if some are unused, unless they start with "_"
* Check is only run if we are in strict mode
* @param {boolean} onlyIfStrict
*/
assertAllUsed(onlyIfStrict = true) {
if (!onlyIfStrict || this.isStrict()) {
for (let [name, entity, used] of this.#values) {
if (!(entity instanceof Scope) && !used) {
const flaggedUnused = name.value.startsWith("_")
if (!used && !(entity instanceof Scope) && !flaggedUnused) {
throw CompilerError.reference(
name.site,
`'${name.toString()}' unused`
)
}
if (flaggedUnused && used) {
throw CompilerError.reference(
name.site,
`_-prefixed variable '${name.toString()}' must be unused`
)
}
}
}
}
Expand Down
34 changes: 34 additions & 0 deletions test/assign.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,40 @@ describe("Assign", () => {
inputs: [int(1)],
output: int(2)
},
{
description: "unused variables throw errors",
fails: /ReferenceError.*'b' unused/,
main: `testing throws_on_unused
func main(a: Int) -> Int {
b = 2;
a
}`,
inputs: [int(1)],
output: int(1)
},
{
description: "underscore-prefix makes unused variables ok",
main: `testing unused_variables_ok_with_underscore
func main(a: Int) -> Int {
_ = 1;
_also_unused = 2;
a + 1
}`,
inputs: [int(1)],
output: int(2)
},
{
description: "used variables must not be underscore-prefixed",
fails: /_-prefixed variable '_thing' must be unused/,
main: `testing used_variables_throw_with_underscore
func main(a: Int) -> Int {
_ = 1;
_thing = 2;
a + _thing
}`,
inputs: [int(1)],
output: int(1)
},
{
description: "rhs enum variant only can be checked",
main: `testing check_enum_variant
Expand Down

0 comments on commit 9a140ae

Please sign in to comment.