PowerShell / PowerShell/PSScriptAnalyzer

New Rule Suggestion: unreachable code,

未关闭
#395 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Issue - New Rule Up-for-Grabs
主要语言
C#
星标
2.2k
派生
414
平均合并
13 小时 1 分钟
30 天内合并 PR
2

描述

Normally, anything after a break or return is unreachable code.

However, it's also possible to have a label after a break, but if you make a mistake typing it, then it's just treated as "anything after a break" and therefore doesn't cause an error.

For example, see this example code full of problems:

:first foreach($i in 0..10) {
    $i *= 10
    Write-Verbose "Imagine we did stuff with $i"
    :mid foreach($j in 0..9) {
        Write-Verbose "Imagine we did stuff with $($i+$j)"
        :inner foreach($k in 0..9) {
            Write-Verbose "Imagine we did stuff with $($i+$j).$k"

            if($k -eq $j) {
                Write-Warning "Peaked at $($i+$j).$k"
                break :mid  # common mistake, will cause no error, acts like a break with no label
                this code is unreachable
            }

           if($k -gt $i) {
                Write-Warning "Ended at $($i+$j).$k"
                break top # uncommon mistake, also no error, breaks out of all loops
           }
       }
    }
}

return

Since this code never runs...
You could write anything that parses like a command and get no errors.

So, my suggestion:

First of all, flag unreachable code.

If there's code after a break or continue or return ... that merits a warning (or information, or something).

Most importantly, flag possible bad labels.

Any time break is followed on the same line by something that is not a comment ... that something should match the name of one of the labels, sans-punctuation.of any sort.

It's possible you could write break top without a corresponding :top label, but it's a bad idea.

Other than that, there's no valid reason why someone would exploit the inconsistency of the language parser here and use punctuation or something like break -this is a comment ...

This should be an error I think, because it's almost guaranteed to be a mistake.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

使用 issue 中的 PowerShell 示例作为行为案例:应报告 break、continue 或 return 之后的不可达语句,并根据已声明的标签验证 break 之后的标签。检查 analyzer 现有的规则入口点和测试,以确定控制流和标签处理应归属于何处;当两种错误模式都能在没有误报的情况下产生预期诊断时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
powershell
领域
devtools
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。