packages feed

ShellCheck 0.10.0 → 0.12.0

raw patch · 27 files changed

Files

CHANGELOG.md view
@@ -1,3 +1,78 @@+## v0.12.0 - 2026-12-02+### Added+- Add `--files-from` option to read input files from a file+- Add `--extended-analysis=local` directive/flag to run dataflow analysis+  on the current script only, without considering any `source`d includes.+- `--list-optional` now lists the SC error code for optional checks+- Support EditorConfig `shellcheck.*` keys+- SC2336: Suggest `cp -R` over implementation specific `cp -r`+- SC2337: Warn about `grep -q` in pipelines under pipefail+- SC2338: Optionally suggest `[[ x == y ]]` over `[[ x = y ]]`+  (bash `require-double-equals`)+- SC2339/SC2340/SC2341/SC3426: Improved exit/return validation across shells++### Changed+- SC2024/SC2232: sudo redirection/builtin now also apply to doas and run0+- SC2114/SC2115: Unintentional `rm` warning now also triggers on globs like+  `rm /bin/*$empty*` and non-canonical paths like `rm -rf /home/foo/$empty/..`+- SC2236/SC2237: warning for negated -n/-z in `[ ]` now also triggers for `test`+- SC2312: `cmd || echo ..` is now considered handling failure+- SC3040: Support `pipefail` as specified in POSIX.1-2024++### Fixed+- `|&` now parses correctly as coprocess separator it Ksh+- Malformed shebangs retain warnings, but are no longer counted as shebangs+- `json1` output no longer contains duplicates instances of warnings+- SC1072 about an invalid `disable=` value now names the value instead+  of a missing `=`+- SC2031: No longer warns that assignments to `_` may be lost in a subshell+- SC2034: Unused variables no longer warn when `allexport` is enabled+- SC2035: Unprotected globs no longer warn when `noglob` is enabled+- SC2064: readonly variables no longer warn about expanding in `trap`+- SC2147: Check for tilde in $PATH now also triggers for declare/local/export+- SC2164: Status of `cd` is considered handled when returned from a function+- SC2178: Overwriting built-in bash arrays no longer warns in non-bash shells+- SC2185: `find -files0-from` no longer triggers check about missing path+- SC2218: Won't trigger on `bats` tests invoking functions defined later+- SC2317: No longer reports commands as unreachable when a `case` catch-all+  is followed by `;;&` and a non-default final clause+- SC3001: busybox sh now considered to support `<(process substitution)`++### Removed+- SC3003: removed since ANSI C string is specified in POSIX.1-2024+++## v0.11.0 - 2025-08-03+### Added+- SC2327/SC2328: Warn about capturing the output of redirected commands.+- SC2329: Warn when (non-escaping) functions are never invoked.+- SC2330: Warn about unsupported glob matches with [[ .. ]] in BusyBox.+- SC2331: Suggest using standard -e instead of unary -a in tests.+- SC2332: Warn about `[ ! -o opt ]` being unconditionally true in Bash.+- SC3062: Warn about bashism `[ -o opt ]`.+- Optional `avoid-negated-conditions`: suggest replacing `[ ! a -eq b ]`+  with `[ a -ne b ]`, and similar for -ge/-lt/=/!=/etc (SC2335).+- Precompiled binaries for Linux riscv64 (linux.riscv64)++### Changed+- SC2002 about Useless Use Of Cat is now disabled by default. It can be+  re-enabled with `--enable=useless-use-of-cat` or equivalent directive.+- SC2236/SC2237 about replacing `[ ! -n .. ]` with `[ -z ]` and vice versa+  is now optional under `avoid-negated-conditions`.+- SC2015 about `A && B || C` no longer triggers when B is a test command.+- SC3012: Do not warn about `\<` and `\>` in test/[] as specified in POSIX.1-2024+- Diff output now uses / as path separator on Windows++### Fixed+- SC2218 about function use-before-define is now more accurate.+- SC2317 about unreachable commands is now less spammy for nested ones.+- SC2292, optional suggestion for [[ ]], now triggers for Busybox.+- Updates for Bash 5.3, including `${| cmd; }` and `source -p`++### Removed+- SC3013: removed since the operators `-ot/-nt/-ef` are specified in POSIX.1-2024++ ## v0.10.0 - 2024-03-07 ### Added - Precompiled binaries for macOS ARM64 (darwin.aarch64)
README.md view
@@ -110,9 +110,11 @@ * [Codacy](https://www.codacy.com/) * [Code Climate](https://codeclimate.com/) * [Code Factor](https://www.codefactor.io/)+* [Codety](https://www.codety.io/) via the [Codety Scanner](https://github.com/codetyio/codety-scanner) * [CircleCI](https://circleci.com) via the [ShellCheck Orb](https://circleci.com/orbs/registry/orb/circleci/shellcheck) * [Github](https://github.com/features/actions) (only Linux)-* [Trunk Check](https://trunk.io/products/check) (universal linter; [allows you to explicitly version your shellcheck install](https://github.com/trunk-io/plugins/blob/bcbb361dcdbe4619af51ea7db474d7fb87540d20/.trunk/trunk.yaml#L32)) via the [shellcheck plugin](https://github.com/trunk-io/plugins/blob/main/linters/shellcheck/plugin.yaml)+* [Trunk Code Quality](https://trunk.io/code-quality) (universal linter; [allows you to explicitly version your shellcheck install](https://github.com/trunk-io/plugins/blob/bcbb361dcdbe4619af51ea7db474d7fb87540d20/.trunk/trunk.yaml#L32)) via the [shellcheck plugin](https://github.com/trunk-io/plugins/blob/main/linters/shellcheck/plugin.yaml)+* [CodeRabbit](https://coderabbit.ai/)  Most other services, including [GitLab](https://about.gitlab.com/), let you install ShellCheck yourself, either through the system's package manager (see [Installing](#installing)),@@ -223,25 +225,34 @@  or use `koalaman/shellcheck-alpine` if you want a larger Alpine Linux based image to extend. It works exactly like a regular Alpine image, but has shellcheck preinstalled. +Using [mise](https://mise.jdx.dev):+```sh+mise use shellcheck+```+ Using the [nix package manager](https://nixos.org/nix): ```sh nix-env -iA nixpkgs.shellcheck ``` +Using the [Flox package manager](https://flox.dev/)+```sh+flox install shellcheck+```+ Alternatively, you can download pre-compiled binaries for the latest release here:  * [Linux, x86_64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.x86_64.tar.xz) (statically linked) * [Linux, armv6hf](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.armv6hf.tar.xz), i.e. Raspberry Pi (statically linked) * [Linux, aarch64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.aarch64.tar.xz) aka ARM64 (statically linked)+* [Linux, riscv64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.riscv64.tar.xz) (statically linked)+* [macOS, aarch64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.darwin.aarch64.tar.xz) * [macOS, x86_64](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.darwin.x86_64.tar.xz) * [Windows, x86](https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.zip)  or see the [GitHub Releases](https://github.com/koalaman/shellcheck/releases) for other releases (including the [latest](https://github.com/koalaman/shellcheck/releases/tag/latest) meta-release for daily git builds). -There are currently no official binaries for Apple Silicon, but third party builds are available via-[ShellCheck for Visual Studio Code](https://github.com/vscode-shellcheck/shellcheck-binaries/releases).- Distro packages already come with a `man` page. If you are building from source, it can be installed with:  ```console@@ -256,7 +267,7 @@ ``` repos: -   repo: https://github.com/koalaman/shellcheck-precommit-    rev: v0.7.2+    rev: v0.11.0     hooks:     -   id: shellcheck #       args: ["--severity=warning"]  # Optionally only show errors and warnings@@ -398,7 +409,7 @@ while read h; do ssh "$h" uptime  # Commands eating while loop input alias archive='mv $1 /backup'     # Defining aliases with arguments tr -cd '[a-zA-Z0-9]'              # [] around ranges in tr-exec foo; echo "Done!"            # Misused 'exec'+exec foo; bar                     # Misused 'exec' find -name \*.bak -o -name \*~ -delete  # Implicit precedence in find # find . -exec foo > bar \;       # Redirections in find f() { whoami; }; sudo f           # External use of internal functions@@ -437,7 +448,7 @@ echo $[1+2]                       # Use standard $((..)) instead of old $[] echo $(($RANDOM % 6))             # Don't use $ on variables in $((..)) echo "$(date)"                    # Useless use of echo-cat file | grep foo               # Useless use of cat+cat file | grep foo               # Useless use of cat (optional check) ```  ### Data and typing errors@@ -510,7 +521,8 @@ [ x$var = xval ]                  # Antiquated x-comparisons ls() { ls -l "$@"; }              # Infinitely recursive wrapper alias ls='ls -l'; ls foo          # Alias used before it takes effect-for x; do for x; do               # Nested loop uses same variable+for x; do for x; do               # Nested loop uses same variable name+set -o pipefail; cmd | grep -q x  # pipefail interferes with grep -q while getopts "a" f; do case $f in "b") # Unhandled getopts flags ``` 
ShellCheck.cabal view
@@ -1,5 +1,5 @@ Name:             ShellCheck-Version:          0.10.0+Version:          0.12.0 Synopsis:         Shell script analysis tool License:          GPL-3 License-file:     LICENSE@@ -22,6 +22,8 @@   * To point out subtle caveats, corner cases and pitfalls, that may cause an     advanced user's otherwise working script to fail under future circumstances. +tested-with: GHC == 8.0, GHC == 8.10, GHC == 9.0.1, GHC == 9.4.7, GHC == 9.6.6+ Extra-Doc-Files:     README.md     CHANGELOG.md@@ -37,8 +39,12 @@  source-repository head     type: git-    location: git://github.com/koalaman/shellcheck.git+    location: https://github.com/koalaman/shellcheck.git +flag dev-mode+    manual: True+    default: False+ library     hs-source-dirs: src     if impl(ghc < 8.0)@@ -46,27 +52,24 @@         semigroups     build-depends:       -- The lower bounds are based on GHC 7.10.3-      -- The upper bounds are based on GHC 9.8.1-      aeson                >= 1.4.0 && < 2.3,+      -- The upper bounds are based on GHC 9.14.1+      aeson                >= 1.4.0 && < 2.4,       array                >= 0.5.1 && < 0.6,       base                 >= 4.8.0.0 && < 5,       bytestring           >= 0.10.6 && < 0.13,-      containers           >= 0.5.6 && < 0.8,-      deepseq              >= 1.4.1 && < 1.6,-      Diff                 >= 0.4.0 && < 0.6,-      fgl                  (>= 5.7.0 && < 5.8.1.0) || (>= 5.8.1.1 && < 5.9),-      filepath             >= 1.4.0 && < 1.5,+      containers           >= 0.5.6 && < 0.9,+      deepseq              >= 1.4.2 && < 1.6,+      Diff                 >= 0.4.0 && < 2.1,+      fgl                  >= 5.8.1.1 && < 5.9,+      filepath             >= 1.4.0 && < 1.6,       mtl                  >= 2.2.2 && < 2.4,       parsec               >= 3.1.14 && < 3.2,-      QuickCheck           >= 2.14.2 && < 2.15,+      QuickCheck           >= 2.14.2 && < 2.20,       regex-tdfa           >= 1.2.0 && < 1.4,       transformers         >= 0.4.2 && < 0.7, -      -- getXdgDirectory from 1.2.3.0-      directory            >= 1.2.3 && < 1.4,--      -- When cabal supports it, move this to setup-depends:-      process+      -- pathIsSymbolicLink from 1.3.0.0+      directory            >= 1.3 && < 1.4     exposed-modules:       ShellCheck.AST       ShellCheck.ASTLib@@ -81,7 +84,7 @@       ShellCheck.Checks.Custom       ShellCheck.Checks.ShellSupport       ShellCheck.Data-      ShellCheck.Debug+      ShellCheck.EditorConfig       ShellCheck.Fixer       ShellCheck.Formatter.Format       ShellCheck.Formatter.CheckStyle@@ -95,9 +98,14 @@       ShellCheck.Parser       ShellCheck.Prelude       ShellCheck.Regex++    if flag(dev-mode)+      exposed-modules:+        ShellCheck.Debug+     other-modules:       Paths_ShellCheck-    default-language: Haskell98+    default-language: Haskell2010  executable shellcheck     if impl(ghc < 8.0)@@ -120,9 +128,21 @@       regex-tdfa,       transformers,       ShellCheck-    default-language: Haskell98+    default-language: Haskell2010     main-is: shellcheck.hs +executable shellcheck-dev+    if flag(dev-mode)+      buildable: True+    else+      buildable: False+    build-depends:+      base,+      containers,+      ShellCheck+    default-language: Haskell2010+    main-is: shellcheck-dev.hs+ test-suite test-shellcheck     type: exitcode-stdio-1.0     build-depends:@@ -142,5 +162,5 @@       regex-tdfa,       transformers,       ShellCheck-    default-language: Haskell98+    default-language: Haskell2010     main-is: test/shellcheck.hs
+ shellcheck-dev.hs view
@@ -0,0 +1,52 @@+{-+    Copyright 2026 Vidar Holen++    This file is part of ShellCheck.+    https://www.shellcheck.net++    ShellCheck is free software: you can redistribute it and/or modify+    it under the terms of the GNU General Public License as published by+    the Free Software Foundation, either version 3 of the License, or+    (at your option) any later version.++    ShellCheck is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <https://www.gnu.org/licenses/>.+-}++-- shellcheck-dev is primarily meant for the potential benefits of AI.+-- It can be run with `cabal run -fdev-mode shellcheck-dev -- ast 'myshellcommand'`++import ShellCheck.Debug+import System.Environment+import System.Exit+import System.IO+import Data.List+import qualified Data.Map as Map++commands :: Map.Map String (String -> String)+commands = Map.fromList [+    ("ast", show . stringToAst)+    ]++validCommands :: String+validCommands = intercalate ", " $ Map.keys commands++putStrLnErr = hPutStrLn stderr++main = do+    args <- getArgs+    case args of+        [cmd, arg] ->+            case Map.lookup cmd commands of+                Just f -> putStrLn $ f arg+                Nothing -> do+                    putStrLnErr $ "Unknown command. Try one of: " ++ validCommands+                    exitFailure+        _ -> do+            putStrLnErr $ "Usage: shellcheck-dev command argument, where command is: " ++ validCommands+            exitFailure
shellcheck.1.md view
@@ -6,7 +6,7 @@  # SYNOPSIS -**shellcheck** [*OPTIONS*...] *FILES*...+**shellcheck** [*OPTIONS*...] [--files-from=FILE] *FILES*...  # DESCRIPTION @@ -39,9 +39,9 @@  **-C**[*WHEN*],\ **--color**[=*WHEN*] -:   For TTY output, enable colors *always*, *never* or *auto*. The default-    is *auto*. **--color** without an argument is equivalent to-    **--color=always**.+:   For **tty** and **diff** output, enable colors *always*, *never* or+    *auto*. The default is *auto*. **--color** without an argument is+    equivalent to **--color=always**.  **-i**\ *CODE1*[,*CODE2*...],\ **--include=***CODE1*[,*CODE2*...] @@ -56,19 +56,28 @@     options are cumulative, but all the codes can be specified at once,     comma-separated as a single argument. -**--extended-analysis=true/false**+**--extended-analysis=full/local/none** -:   Enable/disable Dataflow Analysis to identify more issues (default true). If+:   Enable/disable Dataflow Analysis to identify more issues (default full). If     ShellCheck uses too much CPU/RAM when checking scripts with several-    thousand lines of code, extended analysis can be disabled with this flag-    or a directive. This flag overrides directives and rc files.+    thousand lines of code, extended analysis can be either limited or+    disabled with this flag or a corresponding directive. +    Use `full` for full analysis, `local` to ignore sourced files, or `none` to+    disable. For compatibility, `true` means `full` while `false` means `none`.++    This flag overrides directives and rc files.+ **-f** *FORMAT*, **--format=***FORMAT*  :   Specify the output format of shellcheck, which prints its results in the     standard output. Subsequent **-f** options are ignored, see **FORMATS**     below for more information. +**--help**++:   Show a usage summary and exit.+ **--list-optional**  :   Output a list of known optional checks. These can be enabled with **-o**@@ -76,12 +85,14 @@  **--norc** -:   Don't try to look for .shellcheckrc configuration files.+:   Don't try to look for .shellcheckrc or .editorconfig configuration files.+    This also disables **--rcfile**. ---rcfile\ RCFILE+**--rcfile** *RCFILE*  :   Prefer the specified configuration file over searching for one-    in the default locations.+    in the default locations. The specified file is not read if+    **--norc** is also given.  **-o**\ *NAME1*[,*NAME2*...],\ **--enable=***NAME1*[,*NAME2*...] @@ -92,7 +103,7 @@ **-P**\ *SOURCEPATH*,\ **--source-path=***SOURCEPATH*  :   Specify paths to search for sourced files, separated by `:` on Unix and-    `;` on Windows. This is equivalent to specifying `search-path`+    `;` on Windows. This is equivalent to specifying `source-path`     directives.  **-s**\ *shell*,\ **--shell=***shell*@@ -116,7 +127,7 @@ **-W** *NUM*,\ **--wiki-link-count=NUM**  :   For TTY output, show *NUM* wiki links to more information about mentioned-    warnings. Set to 0 to disable them entirely.+    warnings. The default is 3. Set to 0 to disable them entirely.  **-x**,\ **--external-sources** @@ -132,7 +143,13 @@  :   One or more script files to check, or "-" for standard input. +**--files-from** *FILE* +:   Read a list of files to check from *FILE*. Each line should contain one+    file path. Lines starting with `#` or empty lines are ignored. Use `-` to+    read the list from standard input. This option is processed in addition to+    any files specified on the command line.+ # FORMATS  **tty**@@ -147,7 +164,7 @@     For example, in Vim, `:set makeprg=shellcheck\ -f\ gcc\ %` will allow     using `:make` to check the script, and `:cnext` to jump to the next error. -        <file>:<line>:<column>: <type>: <message>+        <file>:<line>:<column>: <type>: <message> [SC####]  **checkstyle** @@ -184,7 +201,6 @@              && echo -e 'Playlist $f contains a HQ file in mp3 format'          done - **json1**  :   Json is a popular serialization format that is more suitable for web@@ -196,15 +212,23 @@             {               "file": "filename",               "line": lineNumber,+              "endLine": endLineNumber,               "column": columnNumber,+              "endColumn": endColumnNumber,               "level": "severitylevel",               "code": errorCode,-              "message": "warning message"+              "message": "warning message",+              "fix": fixOrNull             },             ...           ]         } +    Each comment covers the whole range it refers to, so `endLine` and+    `endColumn` are always present. `fix` is `null` unless an automatic+    fix is available, in which case it is an object with a `replacements`+    array.+ **json**  :   This is a legacy version of the **json1** format. It's a raw array of@@ -215,7 +239,6 @@ :   Suppress all normal output. Exit with zero if no issues are found,     otherwise exit with one. Stops processing after the first issue. - # DIRECTIVES  ShellCheck directives can be specified as comments in the shell script.@@ -249,7 +272,9 @@ :   Disables a comma separated list of error codes for the following command.     The command can be a simple command like `echo foo`, or a compound command     like a function definition, subshell block or loop. A range can be-    be specified with a dash, e.g. `disable=SC3000-SC4000` to exclude 3xxx.+    specified with a dash, e.g. `disable=SC3000-SC4000` to exclude 3xxx.+    The end of the range is exclusive: this example covers SC3000 through+    SC3999, but not SC4000.     All warnings can be disabled with `disable=all`.  **enable**@@ -257,11 +282,16 @@     Only file-wide `enable` directives are considered.  **extended-analysis**-:   Set to true/false to enable/disable dataflow analysis. Specifying-    `# shellcheck extended-analysis=false` in particularly large (2000+ line)+:   Set to full/local/none to control dataflow analysis. `full` (default)+    performs whole-program analysis; `local` performs it per file, treating+    sourced files as opaque boundaries; `none` disables it. Specifying+    `# shellcheck extended-analysis=none` in particularly large (2000+ line)     auto-generated scripts will reduce ShellCheck's resource usage at the-    expense of certain checks. Extended analysis is enabled by default.+    expense of certain checks. `local` bounds memory when many checked files+    source a shared tree of libraries, while keeping per-file dataflow checks. +    For compatibility, `true` and `false` means `full` and `none` respectively.+ **external-sources** :   Set to `true` in `.shellcheckrc` to always allow ShellCheck to open     arbitrary files from 'source' statements (the way most tools do).@@ -286,7 +316,7 @@ **shell** :   Overrides the shell detected from the shebang.  This is useful for     files meant to be included (and thus lacking a shebang), or possibly-    as a more targeted alternative to 'disable=SC2039'.+    as a more targeted alternative to 'disable=SC3000-SC4000'.  # RC FILES @@ -317,17 +347,46 @@     disable=SC2236  If no `.shellcheckrc` is found in any of the parent directories, ShellCheck-will look in `~/.shellcheckrc` followed by the XDG config directory-(usually `~/.config/shellcheckrc`) on Unix, or `%APPDATA%/shellcheckrc` on-Windows. Only the first file found will be used.+checks the following additional paths and uses the first file found: ++ On Unix-like systems, checks for `~/.shellcheckrc` followed by+  `$XDG_CONFIG_HOME/shellcheckrc` (no leading dot). If `$XDG_CONFIG_HOME` is+  unset it defaults to `~/.config`.++ On Windows systems, checks for `%APPDATA%\shellcheckrc` followed by+  `%XDG_CONFIG_HOME%\shellcheckrc`. If `%XDG_CONFIG_HOME%` is unset it defaults+  to `%APPDATA%`, making this path equal to the previous path and a no-op.+ Note for Snap users: the Snap sandbox disallows access to hidden files. Use `shellcheckrc` without the dot instead.  Note for Docker users: ShellCheck will only be able to look for files that are mounted in the container, so `~/.shellcheckrc` will not be read. +# EDITORCONFIG +Unless `--norc` is used, ShellCheck will also look for a file `.editorconfig`+in the script's directory and each parent directory. Any section whose glob+pattern matches the checked file will have its `shellcheck.*` keys read as+directives, with the `shellcheck.` prefix stripped. This uses the same+`key=value` syntax as `.shellcheckrc`.++For example:++    [*.{ebuild,eclass}]+    shellcheck.shell=bash+    shellcheck.disable=SC2034++    [{PKGBUILD,APKBUILD}]+    shellcheck.shell=bash+    shellcheck.disable=SC2034++If no matching directives are found in any `.editorconfig` in the parent+directories, ShellCheck will look in the global default+`$XDG_CONFIG_HOME/editorconfig.ini` (usually `~/.config/editorconfig.ini`).++Directives from `.shellcheckrc`/`shellcheckrc` and from `.editorconfig` are+both applied, with `.shellcheckrc` taking precedence in case of conflicts.+ # ENVIRONMENT VARIABLES  The environment variable `SHELLCHECK_OPTS` can be set with default flags:@@ -397,10 +456,10 @@  # COPYRIGHT -Copyright 2012-2024, Vidar Holen and contributors.+Copyright 2012-2026, Vidar Holen and contributors. Licensed under the GNU General Public License version 3 or later, see https://gnu.org/licenses/gpl.html  # SEE ALSO -sh(1) bash(1)+sh(1), bash(1), dash(1), ksh(1)
shellcheck.hs view
@@ -20,6 +20,7 @@ import qualified ShellCheck.Analyzer import           ShellCheck.Checker import           ShellCheck.Data+import           ShellCheck.EditorConfig import           ShellCheck.Interface import           ShellCheck.Regex @@ -103,14 +104,14 @@     Option "e" ["exclude"]         (ReqArg (Flag "exclude") "CODE1,CODE2..") "Exclude types of warnings",     Option "" ["extended-analysis"]-        (ReqArg (Flag "extended-analysis") "bool") "Perform dataflow analysis (default true)",+        (ReqArg (Flag "extended-analysis") "mode") "Perform dataflow analysis: true|local|false (default true; local treats sourced files as boundaries)",     Option "f" ["format"]         (ReqArg (Flag "format") "FORMAT") $         "Output format (" ++ formatList ++ ")",     Option "" ["list-optional"]         (NoArg $ Flag "list-optional" "true") "List checks disabled by default",     Option "" ["norc"]-        (NoArg $ Flag "norc" "true") "Don't look for .shellcheckrc files",+        (NoArg $ Flag "norc" "true") "Don't look for .shellcheckrc and .editorconfig files",     Option "" ["rcfile"]         (ReqArg (Flag "rcfile") "RCFILE")         "Prefer the specified configuration file over searching for one",@@ -121,8 +122,8 @@         (ReqArg (Flag "source-path") "SOURCEPATHS")         "Specify path when looking for sourced files (\"SCRIPTDIR\" for script's dir)",     Option "s" ["shell"]-        (ReqArg (Flag "shell") "SHELLNAME")-        "Specify dialect (sh, bash, dash, ksh, busybox)",+        (ReqArg (Flag "shell") "SHELLNAME") $+        "Specify dialect (" ++ intercalate ", " supportedShellDialects ++ ")",     Option "S" ["severity"]         (ReqArg (Flag "severity") "SEVERITY")         "Minimum severity of errors to consider (error, warning, info, style)",@@ -134,12 +135,28 @@     Option "x" ["external-sources"]         (NoArg $ Flag "externals" "true") "Allow 'source' outside of FILES",     Option "" ["help"]-        (NoArg $ Flag "help" "true") "Show this usage summary and exit"+        (NoArg $ Flag "help" "true") "Show this usage summary and exit",+    Option "" ["files-from"]+        (ReqArg (Flag "files-from") "FILE")+        "Read input files from FILE (one per line, or '-' for stdin)"     ] getUsageInfo = usageInfo usageHeader options  printErr = lift . hPutStrLn stderr +trim :: String -> String+trim = f . f+  where f = reverse . dropWhile isSpace++parseFileListLines :: String -> [FilePath]+parseFileListLines contents =+    [ line+    | raw <- lines contents+    , let line = trim raw+    , not (null line)+    , not ("#" `isPrefixOf` line)+    ]+ parseArguments :: [String] -> ExceptT Status IO ([Flag], [FilePath]) parseArguments argv =     case getOpt Permute options argv of@@ -208,21 +225,49 @@ process :: [Flag] -> [FilePath] -> ExceptT Status IO Status process flags files = do     options <- foldM (flip parseOption) defaultOptions flags-    verifyFiles files++    let filesFrom = getOptions flags "files-from"+    extra <- fmap concat $ mapM readFilesFrom filesFrom+    let allFiles = extra ++ files++    -- It shouldn't be an error to do --files-from=/dev/null+    when (null filesFrom) $+        verifyFiles allFiles+     let format = fromMaybe "tty" $ getOption flags "format"     let formatters = formats $ formatterOptions options-    formatter <--        case Map.lookup format formatters of-            Nothing -> do-                printErr $ "Unknown format " ++ format-                printErr "Supported formats:"-                mapM_ (printErr . write) $ Map.keys formatters-                throwError SupportFailure-              where write s = "  " ++ s-            Just f -> ExceptT $ fmap Right f-    sys <- lift $ ioInterface options files-    lift $ runFormatter sys formatter options files+    formatter <- case Map.lookup format formatters of+        Nothing -> do+            printErr $ "Unknown format " ++ format+            printErr "Supported formats:"+            mapM_ (printErr . ("  " ++)) $ Map.keys formatters+            throwError SupportFailure+        Just f -> ExceptT $ fmap Right f +    lift $ do+        rcReadFailed <- newIORef False+        sys <- ioInterface options allFiles (writeIORef rcReadFailed True)+        status <- runFormatter sys formatter options allFiles+        failed <- readIORef rcReadFailed+        return $ if failed then RuntimeException else status++  where+    readFilesFrom :: FilePath -> ExceptT Status IO [FilePath]+    readFilesFrom "-" = do+        contents <- lift getContents+        return (parseFileListLines contents)++    readFilesFrom path = do+        result <- liftIO (try (readFile path) :: IO (Either IOException String))+        case result of+            Left e -> do+                printErr $ "Could not read file list: " ++ path ++ ": " ++ show e+                throwError RuntimeException+            Right contents ->+                return (parseFileListLines contents)+++ runFormatter :: SystemInterface IO -> Formatter -> Options -> [FilePath]             -> IO Status runFormatter sys format options files = do@@ -253,11 +298,20 @@             }             result <- checkScript sys checkspec             onResult format result sys+            -- A malformed EditorConfig (invalid 'root' or 'shellcheck.*'+            -- directive) means shellcheck cannot apply the requested+            -- configuration, so it fails rather than silently proceeding.             return $-                if null (crComments result)-                then NoProblems-                else SomeProblems+                if any editorConfigError (crComments result)+                    then SupportFailure+                    else if null (crComments result)+                        then NoProblems+                        else SomeProblems +        editorConfigError pc =+            cCode (pcComment pc) == 1134 &&+                ".editorconfig" `isSuffixOf` posFile (pcStartPos pc)+ parseEnum name value list =     case lookup value list of         Just value -> return value@@ -285,6 +339,7 @@     case flag of         Flag "shell" str ->             fromMaybe (die $ "Unknown shell: " ++ str) $ do+                guard $ str `elem` supportedShellDialects                 shell <- shellForExecutable str                 return $ return options {                             checkSpec = (checkSpec options) {@@ -379,15 +434,23 @@                 rcfile = Just str             } -        Flag "enable" value ->-            let cs = checkSpec options in return options {+        Flag "enable" value -> do+            let checks = filter (not . null) $ split ',' value+            let supported = map cdName ShellCheck.Analyzer.optionalChecks+            let unknown = filter (\name -> name /= "all" && name `notElem` supported) checks+            unless (null unknown) $ do+                printErr $ "Unrecognized optional checks: " ++ intercalate ", " unknown+                printErr "Supported checks: see `shellcheck --list-optional` (or 'all')"+                throwError SupportFailure+            let cs = checkSpec options+            return options {                 checkSpec = cs {-                    csOptionalChecks = (csOptionalChecks cs) ++ split ',' value+                    csOptionalChecks = (csOptionalChecks cs) ++ checks                 }             }          Flag "extended-analysis" str -> do-            value <- parseBool str+            value <- parseExtendedAnalysis str             return options {                 checkSpec = (checkSpec options) {                     csExtendedAnalysis = Just value@@ -397,6 +460,9 @@         -- This flag is handled specially in 'process'         Flag "format" _ -> return options +        -- This flag is handled specially in 'process'+        Flag "files-from" _ -> return options+         Flag str _ -> do             printErr $ "Internal error for --" ++ str ++ ". Please file a bug :("             return options@@ -419,8 +485,21 @@                 printErr $ "Invalid boolean, expected true/false: " ++ str                 throwError SyntaxFailure -ioInterface :: Options -> [FilePath] -> IO (SystemInterface IO)-ioInterface options files = do+    parseExtendedAnalysis str =+        case str of+            -- Legacy values+            "true" -> return ExtendedAnalysisFull+            "false" -> return ExtendedAnalysisNone+            -- New values+            "full" -> return ExtendedAnalysisFull+            "local" -> return ExtendedAnalysisLocal+            "none" -> return ExtendedAnalysisNone+            _ -> do+                printErr $ "Invalid extended-analysis value, expected full/local/none (or historical true=full, false=none): " ++ str+                throwError SyntaxFailure++ioInterface :: Options -> [FilePath] -> IO () -> IO (SystemInterface IO)+ioInterface options files onRcReadFailure = do     inputs <- mapM normalize files     cache <- newIORef emptyCache     configCache <- newIORef ("", Nothing)@@ -470,8 +549,29 @@         fallback path _ = return path  -    -- Returns the name and contents of .shellcheckrc for the given file-    getConfig cache filename =+    -- Returns the name and contents of .shellcheckrc for the given file,+    -- merged with any shellcheck.* directives found in applicable+    -- EditorConfig files.+    getConfig cache filename = do+        rcResult <- getRcConfig cache filename+        ecResult <- getEditorConfig filename+        return $ mergeConfigs filename rcResult ecResult++    mergeConfigs filename rcResult ecResult =+        case (rcResult, ecResult) of+            (Nothing, Nothing) -> Nothing+            (Just (rcPath, rc), Nothing) -> Just (rcPath, rc)+            (Nothing, Just (ecPath, ec)) -> Just (ecPath, ec)+            (Just (rcPath, rc), Just (ecPath, ec)) ->+                if isEditorConfigRejection ec+                    then Just (ecPath, ec)+                    else Just (rcPath, rc ++ "\n" ++ ec)++    isEditorConfigRejection ec =+        all (\l -> null (trim l) || l == "invalid editorconfig value") (lines ec)+++    getRcConfig cache filename =         case rcfile options of             Just file -> do                 -- We have a specified rcfile. Ignore normal rcfile resolution.@@ -479,9 +579,10 @@                 if path == "/"                   then return result                   else do-                    result <- readConfig file-                    when (isNothing result) $+                    result <- readConfig doesFileExist onRcReadFailure file+                    when (isNothing result) $ do                         hPutStrLn stderr $ "Warning: unable to read --rcfile " ++ file+                        onRcReadFailure                     writeIORef cache ("/", result)                     return result @@ -497,15 +598,85 @@                     writeIORef cache (dir, result)                     return result +    -- Look for .editorconfig files in the target file's directory and+    -- all its parents (as per the EditorConfig spec), plus the global+    -- ${XDG_CONFIG_HOME}/editorconfig.ini default. shellcheck.* keys in+    -- matching sections are turned into directives.+    getEditorConfig filename = do+        -- Resolve the directory (to find .editorconfig files) but keep+        -- the leaf filename as-is so that globs match the symlink name+        -- rather than the resolved target.+        let name = takeFileName filename+        dir <- normalize (takeDirectory filename)+        let path = dir </> name+        dirConfigs <- collectDirConfigs dir+        globalConfig <- readGlobalEditorConfig+        let allConfigs = dirConfigs ++ globalConfig+            contributions = concatMap (directivesFor path) allConfigs+        return $ case contributions of+            [] -> Nothing+            ((sourceFile, _):_) -> Just (sourceFile, concatMap snd contributions)+      where+        -- For each EditorConfig file: report any invalid 'root'+        -- declaration (which takes priority) as a rejected config blob,+        -- otherwise yield the matching shellcheck.* directives+        -- (invalid directives are reported by editorConfigDirectives as a+        -- rejected blob so the .shellcheckrc parser emits SC1134).+        directivesFor path (file, contents) =+            let relative = makeRelativeTo (takeDirectory file) path+            in case invalidRootLines contents of+                (badLine:_) ->+                    [(file, replicate (badLine - 1) '\n' ++ "invalid editorconfig value\n")]+                [] ->+                    case editorConfigDirectives contents relative of+                        Nothing -> []+                        Just blob -> [(file, blob)]++        makeRelativeTo dir path =+            case stripPrefix (addTrailingSlash dir) path of+                Just rest -> rest+                Nothing -> takeFileName path++        addTrailingSlash dir+            | null dir = dir+            | last dir == '/' = dir+            | otherwise = dir ++ "/"++        collectDirConfigs dir = do+            current <- readConfig doesFileExist (return ()) (dir </> ".editorconfig")+            let isRoot = maybe False (isEditorConfigRoot . snd) current+                next = takeDirectory dir+            rest <- if next /= dir && not isRoot+                    then collectDirConfigs next+                    else return []+            return $ maybeToList current ++ rest++        readGlobalEditorConfig = do+            path <- (getXdgDirectory XdgConfig "editorconfig.ini")+                        `catch` ((const $ return "") :: IOException -> IO FilePath)+            if null path+              then return []+              else maybeToList <$> readConfig doesFileExist (return ()) path+     findConfig paths =         case paths of             (file:rest) -> do-                contents <- readConfig file+                contents <- readConfig rcFileExists onRcReadFailure file                 if isJust contents                   then return contents                   else findConfig rest             [] -> return Nothing +    -- A dangling symlink is a configured path even though its target is absent.+    rcFileExists file = do+        exists <- doesFileExist file+        if exists+          then return True+          else do+            link <- pathIsSymbolicLink file `catch`+                ((const $ return False) :: IOException -> IO Bool)+            if link then not <$> doesDirectoryExist file else return False+     -- Get a list of candidate filenames. This includes .shellcheckrc     -- in all parent directories, plus the user's home dir and xdg dir.     -- The dot is optional for Windows and Snap users.@@ -522,8 +693,8 @@         xdg <- getXdgDirectory XdgConfig "shellcheckrc"         return [home, xdg] -    readConfig file = do-        exists <- doesFileExist file+    readConfig fileExists onReadFailure file = do+        exists <- fileExists file         if exists           then do             (contents, _) <- inputFile file `catch` handler file@@ -534,6 +705,7 @@         handler :: FilePath -> IOException -> IO (String, Bool)         handler file err = do             hPutStrLn stderr $ file ++ ": " ++ show err+            onReadFailure             return ("", True)      andM a b arg = do@@ -629,6 +801,8 @@     list = sortOn cdName ShellCheck.Analyzer.optionalChecks     f item = do         putStrLn $ "name:    " ++ cdName item+        putStrLn $ "id:      " ++ intercalate ", " ["SC" ++ show n | n <- cdId item]+        putStrLn $ "wiki:    " ++ intercalate ", " [ShellCheck.Formatter.TTY.wikiLink ++ "SC" ++ show n | n <- cdId item]         putStrLn $ "desc:    " ++ cdDescription item         putStrLn $ "example: " ++ cdPositive item         putStrLn $ "fix:     " ++ cdNegative item
src/ShellCheck/AST.hs view
@@ -31,6 +31,7 @@  data Quoted = Quoted | Unquoted deriving (Show, Eq) data Dashed = Dashed | Undashed deriving (Show, Eq)+data Piped = Piped | Unpiped deriving (Show, Eq) data AssignmentMode = Assign | Append deriving (Show, Eq) newtype FunctionKeyword = FunctionKeyword Bool deriving (Show, Eq) newtype FunctionParentheses = FunctionParentheses Bool deriving (Show, Eq)@@ -64,6 +65,7 @@     | Inner_T_UnparsedIndex SourcePos String     | Inner_T_Assignment AssignmentMode String [t] t     | Inner_T_Backgrounded t+    | Inner_T_KshCoprocess t     | Inner_T_Backticked [t]     | Inner_T_Bang     | Inner_T_Banged t@@ -72,7 +74,7 @@     | Inner_T_CLOBBER     | Inner_T_Case     | Inner_T_CaseExpression t [(CaseType, [t], [t])]-    | Inner_T_Condition ConditionType t+    | Inner_T_Condition ConditionType ConditionType t     | Inner_T_DGREAT     | Inner_T_DLESS     | Inner_T_DLESSDASH@@ -84,7 +86,7 @@     | Inner_T_DollarDoubleQuoted [t]     | Inner_T_DollarExpansion [t]     | Inner_T_DollarSingleQuoted String-    | Inner_T_DollarBraceCommandExpansion [t]+    | Inner_T_DollarBraceCommandExpansion Piped [t]     | Inner_T_Done     | Inner_T_DoubleQuoted [t]     | Inner_T_EOF@@ -138,7 +140,7 @@     | Inner_T_WhileExpression [t] [t]     | Inner_T_Annotation [Annotation] t     | Inner_T_Pipe String-    | Inner_T_CoProc (Maybe String) t+    | Inner_T_CoProc (Maybe Token) t     | Inner_T_CoProcBody t     | Inner_T_Include t     | Inner_T_SourceCommand t t@@ -152,8 +154,12 @@     | ShellOverride String     | SourcePath String     | ExternalSources Bool-    | ExtendedAnalysis Bool+    | ExtendedAnalysis ExtendedAnalysisAnnotation     deriving (Show, Eq)++-- ShellCheck.Interface has an equivalent one used externally, but it would be a circular dependency+data ExtendedAnalysisAnnotation = EAANone | EAALocal | EAAFull deriving (Show, Eq)+ data ConditionType = DoubleBracket | SingleBracket deriving (Show, Eq)  pattern T_AND_IF id = OuterToken id Inner_T_AND_IF@@ -206,12 +212,13 @@ pattern T_Arithmetic id c = OuterToken id (Inner_T_Arithmetic c) pattern T_Array id t = OuterToken id (Inner_T_Array t) pattern TA_Sequence id l = OuterToken id (Inner_TA_Sequence l)-pattern TA_Parentesis id t = OuterToken id (Inner_TA_Parenthesis t)+pattern TA_Parenthesis id t = OuterToken id (Inner_TA_Parenthesis t) pattern T_Assignment id mode var indices value = OuterToken id (Inner_T_Assignment mode var indices value) pattern TA_Trinary id t1 t2 t3 = OuterToken id (Inner_TA_Trinary t1 t2 t3) pattern TA_Unary id op t1 = OuterToken id (Inner_TA_Unary op t1) pattern TA_Variable id str t = OuterToken id (Inner_TA_Variable str t) pattern T_Backgrounded id l = OuterToken id (Inner_T_Backgrounded l)+pattern T_KshCoprocess id l = OuterToken id (Inner_T_KshCoprocess l) pattern T_Backticked id list = OuterToken id (Inner_T_Backticked list) pattern T_Banged id l = OuterToken id (Inner_T_Banged l) pattern T_BatsTest id name t = OuterToken id (Inner_T_BatsTest name t)@@ -222,13 +229,13 @@ pattern TC_Binary id typ op lhs rhs = OuterToken id (Inner_TC_Binary typ op lhs rhs) pattern TC_Group id typ token = OuterToken id (Inner_TC_Group typ token) pattern TC_Nullary id typ token = OuterToken id (Inner_TC_Nullary typ token)-pattern T_Condition id typ token = OuterToken id (Inner_T_Condition typ token)+pattern T_Condition id typ close token = OuterToken id (Inner_T_Condition typ close token) pattern T_CoProcBody id t = OuterToken id (Inner_T_CoProcBody t) pattern T_CoProc id var body = OuterToken id (Inner_T_CoProc var body) pattern TC_Or id typ str t1 t2 = OuterToken id (Inner_TC_Or typ str t1 t2) pattern TC_Unary id typ op token = OuterToken id (Inner_TC_Unary typ op token) pattern T_DollarArithmetic id c = OuterToken id (Inner_T_DollarArithmetic c)-pattern T_DollarBraceCommandExpansion id list = OuterToken id (Inner_T_DollarBraceCommandExpansion list)+pattern T_DollarBraceCommandExpansion id pipe list = OuterToken id (Inner_T_DollarBraceCommandExpansion pipe list) pattern T_DollarBraced id braced op = OuterToken id (Inner_T_DollarBraced braced op) pattern T_DollarBracket id c = OuterToken id (Inner_T_DollarBracket c) pattern T_DollarDoubleQuoted id list = OuterToken id (Inner_T_DollarDoubleQuoted list)@@ -259,7 +266,7 @@ pattern T_UntilExpression id c l = OuterToken id (Inner_T_UntilExpression c l) pattern T_WhileExpression id c l = OuterToken id (Inner_T_WhileExpression c l) -{-# COMPLETE T_AND_IF, T_Bang, T_Case, TC_Empty, T_CLOBBER, T_DGREAT, T_DLESS, T_DLESSDASH, T_Do, T_DollarSingleQuoted, T_Done, T_DSEMI, T_Elif, T_Else, T_EOF, T_Esac, T_Fi, T_For, T_Glob, T_GREATAND, T_Greater, T_If, T_In, T_Lbrace, T_Less, T_LESSAND, T_LESSGREAT, T_Literal, T_Lparen, T_NEWLINE, T_OR_IF, T_ParamSubSpecialChar, T_Pipe, T_Rbrace, T_Rparen, T_Select, T_Semi, T_SingleQuoted, T_Then, T_UnparsedIndex, T_Until, T_While, TA_Assignment, TA_Binary, TA_Expansion, T_AndIf, T_Annotation, T_Arithmetic, T_Array, TA_Sequence, TA_Parentesis, T_Assignment, TA_Trinary, TA_Unary, TA_Variable, T_Backgrounded, T_Backticked, T_Banged, T_BatsTest, T_BraceExpansion, T_BraceGroup, TC_And, T_CaseExpression, TC_Binary, TC_Group, TC_Nullary, T_Condition, T_CoProcBody, T_CoProc, TC_Or, TC_Unary, T_DollarArithmetic, T_DollarBraceCommandExpansion, T_DollarBraced, T_DollarBracket, T_DollarDoubleQuoted, T_DollarExpansion, T_DoubleQuoted, T_Extglob, T_FdRedirect, T_ForArithmetic, T_ForIn, T_Function, T_HereDoc, T_HereString, T_IfExpression, T_Include, T_IndexedElement, T_IoDuplicate, T_IoFile, T_NormalWord, T_OrIf, T_Pipeline, T_ProcSub, T_Redirecting, T_Script, T_SelectIn, T_SimpleCommand, T_SourceCommand, T_Subshell, T_UntilExpression, T_WhileExpression #-}+{-# COMPLETE T_AND_IF, T_Bang, T_Case, TC_Empty, T_CLOBBER, T_DGREAT, T_DLESS, T_DLESSDASH, T_Do, T_DollarSingleQuoted, T_Done, T_DSEMI, T_Elif, T_Else, T_EOF, T_Esac, T_Fi, T_For, T_Glob, T_GREATAND, T_Greater, T_If, T_In, T_Lbrace, T_Less, T_LESSAND, T_LESSGREAT, T_Literal, T_Lparen, T_NEWLINE, T_OR_IF, T_ParamSubSpecialChar, T_Pipe, T_Rbrace, T_Rparen, T_Select, T_Semi, T_SingleQuoted, T_Then, T_UnparsedIndex, T_Until, T_While, TA_Assignment, TA_Binary, TA_Expansion, T_AndIf, T_Annotation, T_Arithmetic, T_Array, TA_Sequence, TA_Parenthesis, T_Assignment, TA_Trinary, TA_Unary, TA_Variable, T_Backgrounded, T_Backticked, T_Banged, T_BatsTest, T_BraceExpansion, T_BraceGroup, TC_And, T_CaseExpression, TC_Binary, TC_Group, TC_Nullary, T_Condition, T_CoProcBody, T_CoProc, TC_Or, TC_Unary, T_DollarArithmetic, T_DollarBraceCommandExpansion, T_DollarBraced, T_DollarBracket, T_DollarDoubleQuoted, T_DollarExpansion, T_DoubleQuoted, T_Extglob, T_FdRedirect, T_ForArithmetic, T_ForIn, T_Function, T_HereDoc, T_HereString, T_IfExpression, T_Include, T_IndexedElement, T_IoDuplicate, T_IoFile, T_KshCoprocess, T_NormalWord, T_OrIf, T_Pipeline, T_ProcSub, T_Redirecting, T_Script, T_SelectIn, T_SimpleCommand, T_SourceCommand, T_Subshell, T_UntilExpression, T_WhileExpression #-}  instance Eq Token where     OuterToken _ a == OuterToken _ b = a == b
src/ShellCheck/ASTLib.hs view
@@ -33,7 +33,7 @@ import Data.Maybe import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map-import Numeric (showHex)+import Numeric (readHex, readOct, showHex)  import Test.QuickCheck @@ -386,6 +386,16 @@ prop_getLiteralString11 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\1") == Just "\1" prop_getLiteralString12 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\12") == Just "\o12" prop_getLiteralString13 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\123") == Just "\o123"+prop_getLiteralString14 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\e[1mfoo\\E[0mbar") == Just "\ESC[1mfoo\ESC[0mbar"+prop_getLiteralString15 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\?") == Just "?"+prop_getLiteralString16 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u9") == Just "\t"+prop_getLiteralString17 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u2F") == Just "/"+prop_getLiteralString18 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u100") == Just "Ā"+prop_getLiteralString19 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u1d00") == Just "ᴀ"+prop_getLiteralString20 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u1D56C") == Just "ᵖC"+prop_getLiteralString21 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\U9z") == Just "\tz"+prop_getLiteralString22 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\u1d00.") == Just "ᴀ."+prop_getLiteralString23 = getLiteralString (T_DollarSingleQuoted (Id 0) "\\U1D56C") == Just "𝕬"  -- Maybe get the literal value of a token, using a custom function -- to map unrecognized Tokens into strings.@@ -409,43 +419,46 @@             'a' -> '\a' : rest             'b' -> '\b' : rest             'e' -> '\x1B' : rest+            'E' -> '\x1B' : rest             'f' -> '\f' : rest             'n' -> '\n' : rest             'r' -> '\r' : rest             't' -> '\t' : rest             'v' -> '\v' : rest+            '\\' -> '\\' : rest             '\'' -> '\'' : rest             '"' -> '"' : rest-            '\\' -> '\\' : rest+            '?' -> '?' : rest             'x' ->-                case cs of-                    (x:y:more) | isHexDigit x && isHexDigit y ->-                        chr (16*(digitToInt x) + (digitToInt y)) : decodeEscapes more-                    (x:more) | isHexDigit x ->-                        chr (digitToInt x) : decodeEscapes more-                    more -> '\\' : 'x' : decodeEscapes more-            _ | isOctDigit c ->-                let (digits, more) = spanMax isOctDigit 3 (c:cs)-                    num = (parseOct digits) `mod` 256-                in (chr num) : decodeEscapes more-            _ -> '\\' : c : rest+                case readHex (take 2 cs) of+                    [(n, s)] -> chr n : s ++ decodeEscapes (drop 2 cs)+                    _ -> '\\' : 'x' : rest+            'u' ->+                case readHex (take 4 cs) of+                    [(n, s)] -> chr n : s ++ decodeEscapes (drop 4 cs)+                    _ -> '\\' : 'x' : rest+            'U' ->+                case readHex (take 8 cs) of+                    [(n, s)] -> chr n : s ++ decodeEscapes (drop 8 cs)+                    _ -> '\\' : 'x' : rest+            _ ->+                case readOct (c:take 2 cs) of+                    [(n, s)] -> chr (n `mod` 256) : s ++ decodeEscapes (drop 2 cs)+                    _ -> '\\' : c : rest       where         rest = decodeEscapes cs-        parseOct = f 0-          where-            f n "" = n-            f n (c:rest) = f (n * 8 + digitToInt c) rest-        spanMax f n list =-            let (first, second) = span f list-                (prefix, suffix) = splitAt n first-            in-                (prefix, suffix ++ second)     decodeEscapes (c:cs) = c : decodeEscapes cs     decodeEscapes [] = []  -- Is this token a string literal? isLiteral t = isJust $ getLiteralString t +-- Is this token a string literal number?+isLiteralNumber t = fromMaybe False $ do+    s <- getLiteralString t+    guard $ all isDigit s+    return True+ -- Escape user data for messages. -- Messages generally avoid repeating user data, but sometimes it's helpful. e4m = escapeForMessage@@ -555,7 +568,7 @@     case t of         T_DollarExpansion _ [c] -> extract c         T_Backticked _ [c] -> extract c-        T_DollarBraceCommandExpansion _ [c] -> extract c+        T_DollarBraceCommandExpansion _ _ [c] -> extract c         _ -> Nothing   where     extract (T_Pipeline _ _ [cmd]) = getCommandName cmd@@ -610,7 +623,7 @@         T_Annotation _ _ t -> getCommandSequences t          T_DollarExpansion _ cmds -> [cmds]-        T_DollarBraceCommandExpansion _ cmds -> [cmds]+        T_DollarBraceCommandExpansion _ _ cmds -> [cmds]         T_Backticked _ cmds -> [cmds]         _ -> [] @@ -910,7 +923,7 @@         T_Annotation _ list _ -> [s | EnableComment s <- list]         _ -> [] -getExtendedAnalysisDirective :: Token -> Maybe Bool+getExtendedAnalysisDirective :: Token -> Maybe ExtendedAnalysisAnnotation getExtendedAnalysisDirective root =     case root of         T_Annotation _ list _ -> listToMaybe $ [s | ExtendedAnalysis s <- list]
src/ShellCheck/Analytics.hs view
@@ -20,6 +20,7 @@ {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PatternGuards #-}+{-# LANGUAGE NondecreasingIndentation #-} module ShellCheck.Analytics (checker, optionalChecks, ShellCheck.Analytics.runTests) where  import ShellCheck.AST@@ -28,6 +29,7 @@ import ShellCheck.CFG import qualified ShellCheck.CFGAnalysis as CF import ShellCheck.Data+import ShellCheck.Fixer (applyFix) import ShellCheck.Parser import ShellCheck.Prelude import ShellCheck.Interface@@ -39,6 +41,7 @@ import Control.Monad.State import Control.Monad.Writer hiding ((<>)) import Control.Monad.Reader+import Data.Array (listArray) import Data.Char import Data.Functor import Data.Function (on)@@ -103,8 +106,7 @@  nodeChecks :: [Parameters -> Token -> Writer [TokenComment] ()] nodeChecks = [-    checkUuoc-    ,checkPipePitfalls+    checkPipePitfalls     ,checkForInQuoted     ,checkForInLs     ,checkShorthandIf@@ -124,6 +126,7 @@     ,checkCaseAgainstGlob     ,checkCommarrays     ,checkOrNeq+    ,checkAndEq     ,checkEchoWc     ,checkConstantIfs     ,checkPipedAssignment@@ -158,7 +161,6 @@     ,checkWrongArithmeticAssignment     ,checkConditionalAndOrs     ,checkFunctionDeclarations-    ,checkStderrPipe     ,checkOverridingPath     ,checkArrayAsString     ,checkUnsupported@@ -169,6 +171,7 @@     ,checkConcatenatedDollarAt     ,checkTildeInPath     ,checkReadWithoutR+    ,checkCpLegacyR     ,checkLoopVariableReassignment     ,checkTrailingBracket     ,checkReturnAgainstZero@@ -183,7 +186,6 @@     ,checkPipeToNowhere     ,checkForLoopGlobVariables     ,checkSubshelledTests-    ,checkInvertedStringTest     ,checkRedirectionToCommand     ,checkDollarQuoteParen     ,checkUselessBang@@ -204,6 +206,8 @@     ,checkUnnecessaryArithmeticExpansionIndex     ,checkUnnecessaryParens     ,checkPlusEqualsNumber+    ,checkExpansionWithRedirection+    ,checkUnaryTestA     ]  optionalChecks = map fst optionalTreeChecks@@ -212,13 +216,15 @@ prop_verifyOptionalExamples = all check optionalTreeChecks   where     check (desc, check) =-        verifyTree check (cdPositive desc)+        verifyCodesTree check (cdId desc) (cdPositive desc)         && verifyNotTree check (cdNegative desc) + optionalTreeChecks :: [(CheckDescription, (Parameters -> Token -> [TokenComment]))] optionalTreeChecks = [     (newCheckDescription {         cdName = "quote-safe-variables",+        cdId = [2248],         cdDescription = "Suggest quoting variables without metacharacters",         cdPositive = "var=hello; echo $var",         cdNegative = "var=hello; echo \"$var\""@@ -226,13 +232,23 @@      ,(newCheckDescription {         cdName = "avoid-nullary-conditions",+        cdId = [2243, 2244],         cdDescription = "Suggest explicitly using -n in `[ $var ]`",-        cdPositive = "[ \"$var\" ]",-        cdNegative = "[ -n \"$var\" ]"+        cdPositive = "[ \"$var\" ] && [ \"$(cmd)\" ]",+        cdNegative = "[ -n \"$var\" ] && [ -n \"$(cmd)\" ]"     }, nodeChecksToTreeCheck [checkNullaryExpansionTest])      ,(newCheckDescription {+        cdName = "avoid-negated-conditions",+        cdId = [2335],+        cdDescription = "Suggest removing unnecessary comparison negations",+        cdPositive = "[ ! \"$var\" -eq 1 ]",+        cdNegative = "[ \"$var\" -ne 1 ]"+    }, nodeChecksToTreeCheck [checkUnnecessarilyInvertedTest])++    ,(newCheckDescription {         cdName = "add-default-case",+        cdId = [2249],         cdDescription = "Suggest adding a default case in `case` statements",         cdPositive = "case $? in 0) echo 'Success';; esac",         cdNegative = "case $? in 0) echo 'Success';; *) echo 'Fail' ;; esac"@@ -240,6 +256,7 @@      ,(newCheckDescription {         cdName = "require-variable-braces",+        cdId = [2250],         cdDescription = "Suggest putting braces around all variable references",         cdPositive = "var=hello; echo $var",         cdNegative = "var=hello; echo ${var}"@@ -247,6 +264,7 @@      ,(newCheckDescription {         cdName = "check-unassigned-uppercase",+        cdId = [2154],         cdDescription = "Warn when uppercase variables are unassigned",         cdPositive = "echo $VAR",         cdNegative = "VAR=hello; echo $VAR"@@ -254,24 +272,43 @@      ,(newCheckDescription {         cdName = "require-double-brackets",+        cdId = [2292],         cdDescription = "Require [[ and warn about [ in Bash/Ksh",         cdPositive = "[ -e /etc/issue ]",         cdNegative = "[[ -e /etc/issue ]]"     }, checkRequireDoubleBracket)      ,(newCheckDescription {+        cdName = "require-double-equals",+        cdId = [2338],+        cdDescription = "Require == and warn about = in Bash tests",+        cdPositive = "[[ \"$x\" = \"$y\" ]]",+        cdNegative = "[[ \"$x\" == \"$y\" ]]"+    }, checkRequireDoubleEquals)++    ,(newCheckDescription {         cdName = "check-set-e-suppressed",+        cdId = [2310, 2311],         cdDescription = "Notify when set -e is suppressed during function invocation",-        cdPositive = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func && echo ok",-        cdNegative = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func; echo ok"+        cdPositive = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func && echo ok; x=$(func)",+        cdNegative = "set -e; func() { cp *.txt ~/backup; rm *.txt; }; func; echo ok; x=$(set -e; func)"     }, checkSetESuppressed)      ,(newCheckDescription {         cdName = "check-extra-masked-returns",+        cdId = [2312],         cdDescription = "Check for additional cases where exit codes are masked",         cdPositive = "rm -r \"$(get_chroot_dir)/home\"",         cdNegative = "set -e; dir=\"$(get_chroot_dir)\"; rm -r \"$dir/home\""     }, checkExtraMaskedReturns)++    ,(newCheckDescription {+        cdName = "useless-use-of-cat",+        cdId = [2002],+        cdDescription = "Check for Useless Use Of Cat (UUOC)",+        cdPositive = "cat foo | grep bar",+        cdNegative = "grep bar foo"+    }, nodeChecksToTreeCheck [checkUuoc])     ]  optionalCheckMap :: Map.Map String (Parameters -> Token -> [TokenComment])@@ -293,6 +330,16 @@ verifyNotTree :: (Parameters -> Token -> [TokenComment]) -> String -> Bool verifyNotTree f s = producesComments f s == Just False +-- Verify that applying all suggested fixes to the script gives the expected result+verifyTreeFix :: (Parameters -> Token -> [TokenComment]) -> String -> String -> Bool+verifyTreeFix f s expected = fixed == Just (lines expected)+  where+    fixed = do+        comments <- runAndGetComments f s+        let combinedFix = mconcat $ mapMaybe tcFix comments+        let scriptLines = lines s+        return $ applyFix combinedFix (listArray (1, length scriptLines) scriptLines)+ checkCommand str f t@(T_SimpleCommand id _ (cmd:rest))     | t `isCommand` str = f cmd rest checkCommand _ _ _ = return ()@@ -302,9 +349,12 @@ checkUnqualifiedCommand _ _ _ = return ()  verifyCodes :: (Parameters -> Token -> Writer [TokenComment] ()) -> [Code] -> String -> Bool-verifyCodes f l s = codes == Just l+verifyCodes f = verifyCodesTree (runNodeAnalysis f)++verifyCodesTree :: (Parameters -> Token -> [TokenComment]) -> [Code] -> String -> Bool+verifyCodesTree treeCheck l s =+    fmap sort codes == Just (sort l)   where-    treeCheck = runNodeAnalysis f     comments = runAndGetComments treeCheck s     codes = map (cCode . tcComment) <$> comments @@ -332,34 +382,19 @@           lowers = eachDiag b a (mainDiag : lowers) -- lower diagonals           eachDiag a [] diags = []           eachDiag a (bch:bs) (lastDiag:diags) = oneDiag a bs nextDiag lastDiag : eachDiag a bs diags-              where nextDiag = head (tail diags)+              where nextDiag = head (drop 1 diags)           oneDiag a b diagAbove diagBelow = thisdiag               where doDiag [] b nw n w = []                     doDiag a [] nw n w = []-                    doDiag (ach:as) (bch:bs) nw n w = me : doDiag as bs me (tail n) (tail w)+                    doDiag (ach:as) (bch:bs) nw n w = me : doDiag as bs me (drop 1 n) (drop 1 w)                         where me = if ach == bch then nw else 1 + min3 (head w) nw (head n)                     firstelt = 1 + head diagBelow-                    thisdiag = firstelt : doDiag a b firstelt diagAbove (tail diagBelow)+                    thisdiag = firstelt : doDiag a b firstelt diagAbove (drop 1 diagBelow)           lab = length a - length b           min3 x y z = if x < y then x else min y z  hasFloatingPoint params = shellType params == Ksh --- Checks whether the current parent path is part of a condition-isCondition (x NE.:| xs) = foldr go (const False) xs x-  where-    go _ _ T_BatsTest{} = True -- count anything in a @test as conditional-    go parent go_rest child =-        getId child `elem` map getId (getConditionChildren parent) || go_rest parent-    getConditionChildren t =-        case t of-            T_AndIf _ left right -> [left]-            T_OrIf id left right -> [left]-            T_IfExpression id conditions elses -> concatMap (take 1 . reverse . fst) conditions-            T_WhileExpression id c l -> take 1 . reverse $ c-            T_UntilExpression id c l -> take 1 . reverse $ c-            _ -> []- -- helpers to build replacements replaceStart id params n r =     let tp = tokenPositions params@@ -490,15 +525,12 @@   sequence_ $ do     str <- getNormalString val     var:op:_ <- matchRegex regex str-    Map.lookup var references+    guard $ S.member var references     return . warn (getId val) 2100 $         "Use $((..)) for arithmetics, e.g. i=$((i " ++ op ++ " 2))"   where     regex = mkRegex "^([_a-zA-Z][_a-zA-Z0-9]*)([+*-]).+$"-    references = foldl (flip ($)) Map.empty (map insertRef $ variableFlow params)-    insertRef (Assignment (_, _, name, _)) =-        Map.insert name ()-    insertRef _ = Prelude.id+    references = S.fromList [name | Assignment (_, _, name, _) <- variableFlow params]      getNormalString (T_NormalWord _ words) = do         parts <- mapM getLiterals words@@ -754,7 +786,9 @@         when v (mapM_ warnFor $ fromWord w)         case getLiteralString w of             Just "-exec" -> broken r True-            Just "-execdir" -> broken r True+            Just "-execdir" -> broken r True -- n.b. -execdir ;/+ is not defined in POSIX+            Just "-ok" -> broken r True      -- n.b. -ok + is not defined in POSIX+            Just "-okdir" -> broken r True   -- n.b. -okdir ;/+ is not defined in POSIX             Just "+" -> broken r False             Just ";" -> broken r False             _ -> broken r v@@ -794,7 +828,7 @@   where     check t@(T_DollarExpansion _ c) = examine t c     check t@(T_Backticked _ c) = examine t c-    check t@(T_DollarBraceCommandExpansion _ c) = examine t c+    check t@(T_DollarBraceCommandExpansion _ _ c) = examine t c     check _ = return ()     tree = parentMap params     examine t contents =@@ -876,13 +910,16 @@ prop_checkShorthandIf6 = verifyNot checkShorthandIf "if foo && bar || baz; then true; fi" prop_checkShorthandIf7 = verifyNot checkShorthandIf "while foo && bar || baz; do true; done" prop_checkShorthandIf8 = verify checkShorthandIf "if true; then foo && bar || baz; fi"-checkShorthandIf params x@(T_OrIf _ (T_AndIf id _ _) (T_Pipeline _ _ t))-        | not (isOk t || inCondition) =+prop_checkShorthandIf9 = verifyNot checkShorthandIf "foo && [ -x /file ] || bar"+prop_checkShorthandIf10 = verifyNot checkShorthandIf "foo && bar || true"+prop_checkShorthandIf11 = verify checkShorthandIf "foo && bar || false"+checkShorthandIf params x@(T_OrIf _ (T_AndIf id _ b) (T_Pipeline _ _ t))+        | not (isOk t || inCondition) && not (isTestCommand b) =     info id 2015 "Note that A && B || C is not if-then-else. C may run when A is true."   where     isOk [t] = isAssignment t || fromMaybe False (do         name <- getCommandBasename t-        return $ name `elem` ["echo", "exit", "return", "printf"])+        return $ name `elem` ["echo", "exit", "return", "printf", "true", ":"])     isOk _ = False     inCondition = isCondition $ getPath (parentMap params) x checkShorthandIf _ _ = return ()@@ -932,12 +969,18 @@ prop_checkConcatenatedDollarAt3 = verify checkConcatenatedDollarAt "echo $a$@" prop_checkConcatenatedDollarAt4 = verifyNot checkConcatenatedDollarAt "echo $@" prop_checkConcatenatedDollarAt5 = verifyNot checkConcatenatedDollarAt "echo \"${arr[@]}\""+prop_checkConcatenatedDollarAt6 = verifyNot checkConcatenatedDollarAt $ unlines ["echo \"${@}\"\\", "    | cat"]+prop_checkConcatenatedDollarAt7 = verifyNot checkConcatenatedDollarAt $ unlines ["echo \"${arr[@]}\"\\", "    other"]+prop_checkConcatenatedDollarAt8 = verify checkConcatenatedDollarAt "echo \"$@\"''" checkConcatenatedDollarAt p word@T_NormalWord {}     | not $ isQuoteFree (shellType p) (parentMap p) word     || null (drop 1 parts) =         mapM_ for array   where-    parts = getWordParts word+    -- Escaped linefeeds can leave empty unquoted literals in the word.+    parts = filter hasContent $ getWordParts word+    hasContent (T_Literal _ "") = False+    hasContent _ = True     array = find isArrayExpansion parts     for t = err (getId t) 2145 "Argument mixes string and array. Use * or separate argument." checkConcatenatedDollarAt _ _ = return ()@@ -971,33 +1014,34 @@ prop_checkArrayWithoutIndex9 = verifyTree checkArrayWithoutIndex "read -r -a arr <<< 'foo bar'; echo \"$arr\"" prop_checkArrayWithoutIndex10 = verifyTree checkArrayWithoutIndex "read -ra arr <<< 'foo bar'; echo \"$arr\"" prop_checkArrayWithoutIndex11 = verifyNotTree checkArrayWithoutIndex "read -rpfoobar r; r=42"+prop_checkArrayWithoutIndex12 = verifyNotTree checkArrayWithoutIndex "#!/bin/sh\nPIPESTATUS=foo" checkArrayWithoutIndex params _ =-    doVariableFlowAnalysis readF writeF defaultMap (variableFlow params)+    doVariableFlowAnalysis readF writeF defaultSet (variableFlow params)   where-    defaultMap = Map.fromList $ map (\x -> (x,())) arrayVariables+    defaultSet = S.fromList $ if shellType params == Bash then arrayVariables else []     readF _ (T_DollarBraced id _ token) _ = do-        map <- get+        s <- get         return . maybeToList $ do             name <- getLiteralString token-            assigned <- Map.lookup name map+            guard $ S.member name s             return $ makeComment WarningC id 2128                     "Expanding an array without an index only gives the first element."     readF _ _ _ = return []      writeF _ (T_Assignment id mode name [] _) _ (DataString _) = do-        isArray <- gets (Map.member name)+        isArray <- gets (S.member name)         return $ if not isArray then [] else             case mode of                 Assign -> [makeComment WarningC id 2178 "Variable was used as an array but is now assigned a string."]                 Append -> [makeComment WarningC id 2179 "Use array+=(\"item\") to append items to an array."]      writeF _ t name (DataArray _) = do-        modify (Map.insert name ())+        modify (S.insert name)         return []     writeF _ expr name _ = do         if isIndexed expr-          then modify (Map.insert name ())-          else modify (Map.delete name)+          then modify (S.insert name)+          else modify (S.delete name)         return []      isIndexed expr =@@ -1048,6 +1092,9 @@ prop_checkSingleQuotedVariables5 = verifyNot checkSingleQuotedVariables "trap 'echo $SECONDS' EXIT" prop_checkSingleQuotedVariables6 = verifyNot checkSingleQuotedVariables "sed -n '$p'" prop_checkSingleQuotedVariables6a = verify checkSingleQuotedVariables "sed -n '$pattern'"+prop_checkSingleQuotedVariables6b = verifyNot checkSingleQuotedVariables "sed -n -e '/foo/h; ${ g; }'"+prop_checkSingleQuotedVariables6c = verifyNot checkSingleQuotedVariables "sed -e '${a\\\nEOF' -e '}'"+prop_checkSingleQuotedVariables6d = verifyNot checkSingleQuotedVariables "sed -n -e '/0$/h; 42,${' -e G -e '}'" prop_checkSingleQuotedVariables7 = verifyNot checkSingleQuotedVariables "PS1='$PWD \\$ '" prop_checkSingleQuotedVariables8 = verify checkSingleQuotedVariables "find . -exec echo '$1' {} +" prop_checkSingleQuotedVariables9 = verifyNot checkSingleQuotedVariables "find . -exec awk '{print $1}' {} \\;"@@ -1067,6 +1114,15 @@ prop_checkSingleQuotedVariables23 = verifyNot checkSingleQuotedVariables "command jq '$__loc__'" prop_checkSingleQuotedVariables24 = verifyNot checkSingleQuotedVariables "exec jq '$__loc__'" prop_checkSingleQuotedVariables25 = verifyNot checkSingleQuotedVariables "exec -c -a foo jq '$__loc__'"+prop_checkSingleQuotedVariables26 = verifyNot checkSingleQuotedVariables "runc exec ctr sh -c 'echo $HOME'"+prop_checkSingleQuotedVariables27 = verifyNot checkSingleQuotedVariables "run -0 nsenter -t 1 -m /bin/bash -eu -o pipefail -c 'echo $HOME'"+prop_checkSingleQuotedVariables28 = verifyNot checkSingleQuotedVariables "kubectl exec pod -- sh -euc 'echo $HOME'"+prop_checkSingleQuotedVariables29 = verify checkSingleQuotedVariables "runc exec ctr sh -c 'echo $HOME' 'echo $HOME'"+prop_checkSingleQuotedVariables30 = verify checkSingleQuotedVariables "runc exec ctr sh -x 'echo $HOME'"+prop_checkSingleQuotedVariables31 = verify checkSingleQuotedVariables "runc exec ctr sh script -c 'echo $HOME'"+prop_checkSingleQuotedVariables32 = verify checkSingleQuotedVariables "echo sh --rcfile 'echo $HOME'"+prop_checkSingleQuotedVariables33 = verifyNot checkSingleQuotedVariables "chroot /mnt /bin/ksh93 -c 'echo $HOME'"+prop_checkSingleQuotedVariables34 = verifyNot checkSingleQuotedVariables "yq '.a as $x | $x'"   checkSingleQuotedVariables params t@(T_SingleQuoted id s) =@@ -1096,10 +1152,14 @@                 ,"xprop"                 ,"alias"                 ,"sudo" -- covering "sudo sh" and such+                ,"doas" -- same as sudo+                ,"run0" -- same as sudo                 ,"docker" -- like above                 ,"podman"+                ,"oc"                 ,"dpkg-query"                 ,"jq"  -- could also check that user provides --arg+                ,"yq"                 ,"rename"                 ,"rg"                 ,"unset"@@ -1109,7 +1169,24 @@                 ]             || "awk" `isSuffixOf` commandName             || "perl" `isPrefixOf` commandName+            || isShellScriptArgument +    -- Like `runc exec ctr sh -c 'echo $HOME'`+    isShellScriptArgument = fromMaybe False $ do+        T_Redirecting _ _ (T_SimpleCommand _ _ words) <- getClosestCommand parents t+        let pathIds = map getId $ NE.toList $ getPath parents t+        let before = takeWhile (\w -> getId w `notElem` pathIds) words+        return $ any isShellInvocation $ tails $ map (fromMaybe "" . getLiteralString) before+    isShellInvocation (cmd:opts) =+        basename cmd `elem` ["sh", "bash", "dash", "ash", "ksh", "ksh88", "ksh93", "mksh", "oksh", "zsh"] && endsWithDashC opts+    isShellInvocation _ = False+    endsWithDashC opts =+        case opts of+            [flag] -> flag `matches` mkRegex "^-[a-zA-Z]*c[a-zA-Z]*$"+            flag:_:rest | flag `elem` ["-o", "+o", "-O", "+O"] -> endsWithDashC rest+            flag:rest | take 1 flag `elem` ["-", "+"] -> endsWithDashC rest+            _ -> False+     commonlyQuoted = ["PS1", "PS2", "PS3", "PS4", "PROMPT_COMMAND"]     isOkAssignment t =         case t of@@ -1118,11 +1195,11 @@             _ -> False      re = mkRegex "\\$[{(0-9a-zA-Z_]|`[^`]+`"-    sedContra = mkRegex "\\$[{dpsaic]($|[^a-zA-Z])"+    sedContra = mkRegex "\\$[acdgGilpPsxy]($|[^a-zA-Z])|\\$\\{[[:space:]]*($|/|[acdgGilpPsxy]($|[^a-zA-Z]))"      getFindCommand (T_SimpleCommand _ _ words) =         let list = map getLiteralString words-            cmd  = dropWhile (\x -> x /= Just "-exec" && x /= Just "-execdir") list+            cmd  = dropWhile (\x -> x `notElem` map Just ["-exec", "-execdir", "-ok", "-okdir"]) list         in           case cmd of             (flag:cmd:rest) -> fromMaybe "find" cmd@@ -1523,6 +1600,7 @@ prop_checkComparisonAgainstGlob4 = verifyNot checkComparisonAgainstGlob "[ $cow = foo ]" prop_checkComparisonAgainstGlob5 = verify checkComparisonAgainstGlob "[[ $cow != $bar ]]" prop_checkComparisonAgainstGlob6 = verify checkComparisonAgainstGlob "[ $f != /* ]"+prop_checkComparisonAgainstGlob7 = verify checkComparisonAgainstGlob "#!/bin/busybox sh\n[[ $f == *foo* ]]" checkComparisonAgainstGlob _ (TC_Binary _ DoubleBracket op _ (T_NormalWord id [T_DollarBraced _ _ _]))     | op `elem` ["=", "==", "!="] =         warn id 2053 $ "Quote the right-hand side of " ++ op ++ " in [[ ]] to prevent glob matching."@@ -1530,10 +1608,14 @@         | op `elem` ["=", "==", "!="] && isGlob word =     err (getId word) 2081 msg   where-    msg = if isBashLike params+    msg = if (shellType params) `elem` [Bash, Ksh]  -- Busybox does not support glob matching             then "[ .. ] can't match globs. Use [[ .. ]] or case statement."             else "[ .. ] can't match globs. Use a case statement." +checkComparisonAgainstGlob params (TC_Binary _ DoubleBracket op _ word)+        | shellType params == BusyboxSh && op `elem` ["=", "==", "!="] && isGlob word =+    err (getId word) 2330 "BusyBox [[ .. ]] does not support glob matching. Use a case statement."+ checkComparisonAgainstGlob _ _ = return ()  prop_checkCaseAgainstGlob1 = verify checkCaseAgainstGlob "case foo in lol$n) foo;; esac"@@ -1605,7 +1687,7 @@             T_OrIf _ lhs _ -> getExpr lhs -- Fetches x and y in `T_OrIf x (T_OrIf y z)`             T_Pipeline _ _ [x] -> getExpr x             T_Redirecting _ _ c -> getExpr c-            T_Condition _ _ c -> getExpr c+            T_Condition _ _ _ c -> getExpr c             TC_Binary _ _ op lhs rhs -> orient (lhs, op, rhs)             _ -> Nothing @@ -1620,11 +1702,71 @@ checkOrNeq _ _ = return ()  +prop_checkAndEq1 = verifyNot checkAndEq "cow=0; foo=0; if [[ $lol -eq cow && $lol -eq foo ]]; then echo foo; fi"+prop_checkAndEq2 = verifyNot checkAndEq "lol=0 foo=0; (( a==lol && a==foo ))"+prop_checkAndEq3 = verify checkAndEq "[ \"$a\" = lol && \"$a\" = foo ]"+prop_checkAndEq4 = verifyNot checkAndEq "[ a = $cow && b = $foo ]"+prop_checkAndEq5 = verifyNot checkAndEq "[[ $a = /home && $a = */public_html/* ]]"+prop_checkAndEq6 = verify checkAndEq "[ $a = a ] && [ $a = b ]"+prop_checkAndEq7 = verify checkAndEq "[ $a = a ] && [ $a = b ] || true"+prop_checkAndEq8 = verifyNot checkAndEq "[[ $a == x && $a == x ]]"+prop_checkAndEq9 = verifyNot checkAndEq "[ 0 -eq $FOO ] && [ 0 -eq $BAR ]"+prop_checkAndEq10 = verify checkAndEq "(( a == 1 && a == 2 ))"+prop_checkAndEq11 = verify checkAndEq "[ $x -eq 1 ] && [ $x -eq 2 ]"+prop_checkAndEq12 = verify checkAndEq "[ 1 -eq $x ] && [ $x -eq 2 ]"+prop_checkAndEq13 = verifyNot checkAndEq "[ 1 -eq $x ] && [ $x -eq 1 ]"+prop_checkAndEq14 = verifyNot checkAndEq "[ $a = $b ] && [ $a = $c ]"++checkAndEqOperands "-eq" rhs1 rhs2 = isLiteralNumber rhs1 && isLiteralNumber rhs2+checkAndEqOperands op rhs1 rhs2 | op == "=" || op == "=="  = isLiteral rhs1 && isLiteral rhs2+checkAndEqOperands _ _ _ = False++-- For test-level "and": [ x = y -a x = z ]+checkAndEq _ (TC_And id typ op (TC_Binary _ _ op1 lhs1 rhs1 ) (TC_Binary _ _ op2 lhs2 rhs2))+    | op1 == op2 && lhs1 == lhs2 && rhs1 /= rhs2 && checkAndEqOperands op1 rhs1 rhs2 =+        warn id 2333 $ "You probably wanted " ++ (if typ == SingleBracket then "-o" else "||") ++ " here, otherwise it's always false."++-- For arithmetic context "and"+checkAndEq _ (TA_Binary id "&&" (TA_Binary _ "==" lhs1 rhs1) (TA_Binary _ "==" lhs2 rhs2))+    | lhs1 == lhs2 && isLiteralNumber rhs1 && isLiteralNumber rhs2 =+        warn id 2334 "You probably wanted || here, otherwise it's always false."++-- For command level "and": [ x = y ] && [ x = z ]+checkAndEq _ (T_AndIf id lhs rhs) = sequence_ $ do+    (lhs1, op1, rhs1) <- getExpr lhs+    (lhs2, op2, rhs2) <- getExpr rhs+    guard $ op1 == op2+    guard $ lhs1 == lhs2 && rhs1 /= rhs2+    guard $ checkAndEqOperands op1 rhs1 rhs2+    return $ warn id 2333 "You probably wanted || here, otherwise it's always false."+  where+    getExpr x =+        case x of+            T_AndIf _ lhs _ -> getExpr lhs -- Fetches x and y in `T_AndIf x (T_AndIf y z)`+            T_Pipeline _ _ [x] -> getExpr x+            T_Redirecting _ _ c -> getExpr c+            T_Condition _ _ _ c -> getExpr c+            TC_Binary _ _ op lhs rhs -> orient (lhs, op, rhs)+            _ -> Nothing++    -- Swap items so that the constant side is rhs (or Nothing if both/neither is constant)+    orient (lhs, op, rhs) =+        case (isConstant lhs, isConstant rhs) of+            (True, False) -> return (rhs, op, lhs)+            (False, True) -> return (lhs, op, rhs)+            _ -> Nothing+++checkAndEq _ _ = return ()++ prop_checkValidCondOps1 = verify checkValidCondOps "[[ a -xz b ]]" prop_checkValidCondOps2 = verify checkValidCondOps "[ -M a ]" prop_checkValidCondOps2a = verifyNot checkValidCondOps "[ 3 \\> 2 ]" prop_checkValidCondOps3 = verifyNot checkValidCondOps "[ 1 = 2 -a 3 -ge 4 ]" prop_checkValidCondOps4 = verifyNot checkValidCondOps "[[ ! -v foo ]]"+prop_checkValidCondOps5 = verifyNot checkValidCondOps "[ \\! -e foo ]"+prop_checkValidCondOps6 = verifyNot checkValidCondOps "[ '!' -e foo ]" checkValidCondOps _ (TC_Binary id _ s _ _)     | s `notElem` binaryTestOps =         warn id 2057 "Unknown binary operator."@@ -1885,7 +2027,9 @@ prop_checkSpuriousExec9 = verify checkSpuriousExec "for file in rc.d/*; do exec \"$file\"; done" prop_checkSpuriousExec10 = verifyNot checkSpuriousExec "exec file; r=$?; printf >&2 'failed\n'; return $r" prop_checkSpuriousExec11 = verifyNot checkSpuriousExec "exec file; :"-checkSpuriousExec _ = doLists+prop_checkSpuriousExec12 = verifyNot checkSpuriousExec "#!/bin/bash\nshopt -s execfail; exec foo; exec bar; echo 'Error'; exit 1;"+prop_checkSpuriousExec13 = verify checkSpuriousExec "#!/bin/dash\nshopt -s execfail; exec foo; exec bar; echo 'Error'; exit 1;"+checkSpuriousExec params t = when (not $ hasExecfail params) $ doLists t   where     doLists (T_Script _ _ cmds) = doList cmds False     doLists (T_BraceGroup _ cmds) = doList cmds False@@ -1982,20 +2126,39 @@ prop_subshellAssignmentCheck21 = verifyNotTree subshellAssignmentCheck "test1() { echo foo | if [[ $var ]]; then echo $var; fi; }; test2() { echo $var; }" prop_subshellAssignmentCheck22 = verifyNotTree subshellAssignmentCheck "( [[ -n $foo || -z $bar ]] ); echo $foo $bar" prop_subshellAssignmentCheck23 = verifyNotTree subshellAssignmentCheck "( export foo ); echo $foo"+prop_subshellAssignmentCheck24 = verifyNotTree subshellAssignmentCheck "( read -r a _ c <<< 'x y z'; ); echo $_"+prop_subshellAssignmentCheck25 = verifyNotTree subshellAssignmentCheck "( _=discard; ); echo $_"+prop_subshellAssignmentCheck26 = verifyNotTree subshellAssignmentCheck "( a=1; ); f() { echo $a; }"+prop_subshellAssignmentCheck27 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { run true; [ \"$status\" -eq 0 ]; }\nf() { run true; [ \"$status\" -eq 0 ]; }\n@test 'bar' { f; }"+prop_subshellAssignmentCheck28 = verifyTree subshellAssignmentCheck "f() { ( a=1; ); }; echo $a"+prop_subshellAssignmentCheck29 = verifyTree subshellAssignmentCheck "f() { ( a=1; ); echo $a; }"+prop_subshellAssignmentCheck30 = verifyNotTree subshellAssignmentCheck "( f() { a=1; }; ); echo $a"+prop_subshellAssignmentCheck31 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { export a=1; }\n@test 'bar' { export a=2; }"+prop_subshellAssignmentCheck32 = verifyNotTree subshellAssignmentCheck "( a=1; ); declare -x a=2; echo $a"+prop_subshellAssignmentCheck33 = verifyTree subshellAssignmentCheck "( a=1; ); export a+=2"+prop_subshellAssignmentCheck34 = verifyTree subshellAssignmentCheck "f() { cmd | while read x; do n=1; done; }; f; echo $n"+prop_subshellAssignmentCheck35 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { f() { a=1; }; }\n@test 'bar' { f; echo $a; }"+prop_subshellAssignmentCheck40 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { ( run true; ) & run true; echo $status; }"+prop_subshellAssignmentCheck41 = verifyTree subshellAssignmentCheck "( run true; ); echo $status"+prop_subshellAssignmentCheck42 = verifyNotTree subshellAssignmentCheck "#!/usr/bin/env bats\n@test 'foo' { run true | cat; }\n@test 'bar' { true; }" subshellAssignmentCheck params t =     let flow = variableFlow params-        check = findSubshelled flow [("oops",[])] Map.empty+        check = findSubshelled flow [(InSubshell "oops",[])] Map.empty     in execWriter check +data SubshellCheckScope =+    InSubshell String -- The reason for the subshell+    | InFunction (Map.Map String VariableState) -- Variable states outside the function + findSubshelled [] _ _ = return ()-findSubshelled (Assignment x@(_, _, str, data_):rest) scopes@((reason,scope):restscope) deadVars =+findSubshelled (Assignment x@(_, _, str, data_):rest) scopes@((kind,scope):restscope) deadVars =     if isTrueAssignmentSource data_-    then findSubshelled rest ((reason, x:scope):restscope) $ Map.insert str Alive deadVars+    then findSubshelled rest ((kind, x:scope):restscope) $ Map.insert str Alive deadVars     else findSubshelled rest scopes deadVars  findSubshelled (Reference (_, readToken, str):rest) scopes deadVars = do-    unless (shouldIgnore str) $ case Map.findWithDefault Alive str deadVars of+    unless (shouldIgnore str || isAssignedBy readToken) $ case Map.findWithDefault Alive str deadVars of         Alive -> return ()         Dead writeToken reason -> do                     info (getId writeToken) 2030 $ "Modification of " ++ str ++ " is local (to subshell caused by "++ reason ++")."@@ -2003,17 +2166,31 @@     findSubshelled rest scopes deadVars   where     shouldIgnore str =-        str `elem` ["@", "*", "IFS"]+        str `elem` ["@", "*", "_", "IFS"]+    -- `export foo=bar` references foo, but does not read its old value+    isAssignedBy (T_Assignment _ Assign name _ _) = name == str+    isAssignedBy _ = False  findSubshelled (StackScope (SubshellScope reason):rest) scopes deadVars =-    findSubshelled rest ((reason,[]):scopes) deadVars+    findSubshelled rest ((InSubshell reason,[]):scopes) deadVars -findSubshelled (StackScopeEnd:rest) ((reason, scope):oldScopes) deadVars =+-- A function body runs where the function is called, not where it is defined,+-- so subshells preceding the definition don't affect the variables it reads.+findSubshelled (StackScope FunctionScope:rest) scopes deadVars =+    findSubshelled rest ((InFunction deadVars,[]):scopes) Map.empty++findSubshelled (StackScopeEnd:rest) ((InSubshell reason, scope):oldScopes) deadVars =     findSubshelled rest oldScopes $         foldl (\m (_, token, var, _) ->             Map.insert var (Dead token reason) m) deadVars scope +-- Likewise, assignments in a function body are not made where the function is+-- defined, so don't add them to the enclosing scope. Keep the effects of+-- subshells inside the function though.+findSubshelled (StackScopeEnd:rest) ((InFunction outerVars, _):oldScopes) deadVars =+    findSubshelled rest oldScopes $ Map.union deadVars outerVars + -- FIXME: This is a very strange way of doing it. -- For each variable read/write, run a stateful function that emits -- comments. The comments are collected and returned.@@ -2251,11 +2428,11 @@ prop_checkFunctionsUsedExternally2b =   verifyNotTree checkFunctionsUsedExternally "alias f='a'; find . -type f" prop_checkFunctionsUsedExternally2c =-  verifyTree checkFunctionsUsedExternally "alias f='a'; find . -type f -exec f +"+  verifyTree checkFunctionsUsedExternally "alias f='a'; find . -type f -exec f {} +" prop_checkFunctionsUsedExternally3 =   verifyNotTree checkFunctionsUsedExternally "f() { :; }; echo f" prop_checkFunctionsUsedExternally4 =-  verifyNotTree checkFunctionsUsedExternally "foo() { :; }; sudo \"foo\""+  verifyNotTree checkFunctionsUsedExternally "foo() { :; }; run0 \"foo\"" prop_checkFunctionsUsedExternally5 =   verifyTree checkFunctionsUsedExternally "foo() { :; }; ssh host foo" prop_checkFunctionsUsedExternally6 =@@ -2265,7 +2442,9 @@ prop_checkFunctionsUsedExternally8 =   verifyTree checkFunctionsUsedExternally "foo() { :; }; command sudo foo" prop_checkFunctionsUsedExternally9 =-  verifyTree checkFunctionsUsedExternally "foo() { :; }; exec -c sudo foo"+  verifyTree checkFunctionsUsedExternally "foo() { :; }; exec -c doas foo"+prop_checkFunctionsUsedExternally10 =+  verifyTree checkFunctionsUsedExternally "foo() { :; }; timeout -p 10 foo" checkFunctionsUsedExternally params t =     runNodeAnalysis checkCommand params t   where@@ -2289,15 +2468,18 @@             "chroot" -> firstNonFlag             "screen" -> firstNonFlag             "sudo" -> firstNonFlag+            "doas" -> firstNonFlag+            "run0" -> firstNonFlag             "xargs" -> firstNonFlag             "tmux" -> firstNonFlag+            "timeout" -> take 1 $ drop 1 $ dropFlags argAndString             "ssh" -> take 1 $ drop 1 $ dropFlags argAndString             "find" -> take 1 $ drop 1 $                 dropWhile (\x -> fst x `notElem` findExecFlags) argAndString             _ -> []       where         firstNonFlag = take 1 $ dropFlags argAndString-        findExecFlags = ["-exec", "-execdir", "-ok"]+        findExecFlags = ["-exec", "-execdir", "-ok", "-okdir"]         dropFlags = dropWhile (\x -> "-" `isPrefixOf` fst x)      functionsAndAliases = Map.union (functions t) (aliases t)@@ -2369,24 +2551,30 @@ prop_checkUnused49 = verifyNotTree checkUnusedAssignments "declare -A array; key=a; [[ -v array[$key] ]]" prop_checkUnused50 = verifyNotTree checkUnusedAssignments "foofunc() { :; }; typeset -fx foofunc" prop_checkUnused51 = verifyTree checkUnusedAssignments "x[y[z=1]]=1; echo ${x[@]}"+prop_checkUnused52 = verifyNotTree checkUnusedAssignments "set -o allexport\nfoo=bar"+prop_checkUnused53 = verifyNotTree checkUnusedAssignments "run --separate-stderr true"+prop_checkUnused54 = verifyNotTree checkUnusedAssignments "#!/usr/bin/env bats\n@test 'foo' { true; }"+prop_checkUnused55 = verifyTree checkUnusedAssignments "run=1"+prop_checkUnused56 = verifyNotTree checkUnusedAssignments "run foo bar"+prop_checkUnused57 = verifyTree checkUnusedAssignments "#!/usr/bin/env bats\n@test 'foo' { output=$(true); }"  checkUnusedAssignments params t = execWriter (mapM_ warnFor unused)   where     flow = variableFlow params-    references = foldl (flip ($)) defaultMap (map insertRef flow)-    insertRef (Reference (base, token, name)) =-        Map.insert (stripSuffix name) ()-    insertRef _ = id+    references = Map.union (Map.fromList [(stripSuffix name, ()) | Reference (base, token, name) <- flow]) defaultMap -    assignments = foldl (flip ($)) Map.empty (map insertAssignment flow)-    insertAssignment (Assignment (_, token, name, _)) | isVariableName name =-        Map.insert name token-    insertAssignment _ = id+    assignments = Map.fromList [(name, token) | Assignment (base, token, name, _) <- flow, isVariableName name, not $ isBats base]+    -- Variables set by bats' run (or pretended to be set by @test)+    -- are for the caller to check, if needed+    isBats t = case t of+        T_SimpleCommand _ _ (cmd:_) -> getLiteralString cmd == Just "run"+        T_BatsTest {} -> True+        _ -> False      unused = Map.assocs $ Map.difference assignments references      warnFor (name, token) =-        unless ("_" `isPrefixOf` name) $+        unless ("_" `isPrefixOf` name || hasAllexport params) $             warn (getId token) 2034 $                 name ++ " appears unused. Verify use (or export if used externally)." @@ -2445,6 +2633,14 @@ prop_checkUnassignedReferences50 = verifyNotTree checkUnassignedReferences "echo ${foo:+bar}" prop_checkUnassignedReferences51 = verifyNotTree checkUnassignedReferences "echo ${foo:+$foo}" prop_checkUnassignedReferences52 = verifyNotTree checkUnassignedReferences "wait -p pid; echo $pid"+prop_checkUnassignedReferences53 = verifyTree checkUnassignedReferences "x=($foo)"+prop_checkUnassignedReferences54 = verifyNotTree checkUnassignedReferences "f() { run true; echo \"$status $output ${lines[0]}\"; }"+prop_checkUnassignedReferences55 = verifyNotTree checkUnassignedReferences "#!/usr/bin/env bats\n@test 'foo' { run_wrapper; echo \"$status $stderr\"; }"+prop_checkUnassignedReferences56 = verifyTree checkUnassignedReferences "f() { run true; echo $stderr; }"+prop_checkUnassignedReferences57 = verifyNotTree checkUnassignedReferences "f() { run -1 --separate-stderr false; echo \"$stderr ${stderr_lines[0]}\"; }"+prop_checkUnassignedReferences58 = verifyTree checkUnassignedReferences "echo $stderr"+prop_checkUnassignedReferences59 = verifyNotTree checkUnassignedReferences "compgen -V files -G '*'; echo \"${files[@]}\""+prop_checkUnassignedReferences60 = verifyNotTree checkUnassignedReferences "compgen -A function -V funcs; echo \"${funcs[@]}\""  checkUnassignedReferences = checkUnassignedReferences' False checkUnassignedReferences' includeGlobals params t = warnings@@ -2500,14 +2696,12 @@      warnings = execWriter . sequence $ mapMaybe warningFor unassigned -    -- Due to parsing, foo=( [bar]=baz ) parses 'bar' as a reference even for assoc arrays.-    -- Similarly, ${foo[bar baz]} may not be referencing bar/baz. Just skip these.+    -- ${foo[bar baz]} may not be referencing bar/baz. Just skip these.     -- We can also have ${foo:+$foo} should be treated like [[ -n $foo ]] && echo $foo     isException var t = any shouldExclude $ getPath (parentMap params) t       where         shouldExclude t =             case t of-                T_Array {} -> True                 (T_DollarBraced _ _ l) ->                     let str = concat $ oversimplify l                         ref = getBracedReference str@@ -2540,8 +2734,10 @@ prop_checkGlobsAsOptions4 = verifyNot checkGlobsAsOptions "*.txt" prop_checkGlobsAsOptions5 = verifyNot checkGlobsAsOptions "echo 'Files:' *.txt" prop_checkGlobsAsOptions6 = verifyNot checkGlobsAsOptions "printf '%s\\n' *"-checkGlobsAsOptions _ cmd@(T_SimpleCommand _ _ args) =-    unless ((fromMaybe "" $ getCommandBasename cmd) `elem` ["echo", "printf"]) $+prop_checkGlobsAsOptions7 = verifyNot checkGlobsAsOptions "set -f; ls *"+prop_checkGlobsAsOptions8 = verifyNot checkGlobsAsOptions "set -o noglob\nrm *"+checkGlobsAsOptions params cmd@(T_SimpleCommand _ _ args) =+    unless (((fromMaybe "" $ getCommandBasename cmd) `elem` ["echo", "printf"]) || hasNoglob params) $         mapM_ check $ takeWhile (not . isEndOfArgs) (drop 1 args)   where     check v@(T_NormalWord _ (T_Glob id s:_)) | s == "*" || s == "?" =@@ -2719,7 +2915,7 @@ prop_checkCdAndBack7 = verifyNot checkCdAndBack "set -e; for dir in */; do cd \"$dir\"; some_cmd; cd ..; done" prop_checkCdAndBack8 = verifyNot checkCdAndBack "cd tmp\nfoo\n# shellcheck disable=SC2103\ncd ..\n" checkCdAndBack params t =-    unless (hasSetE params) $ mapM_ doList $ getCommandSequences t+    unless (hasErrexit params) $ mapM_ doList $ getCommandSequences t   where     isCdRevert t =         case oversimplify t of@@ -2763,8 +2959,8 @@   where     path = let p = getPath (parentMap params) t in NE.filter relevant p     subshellType t = case leadType params t of-        NoneScope -> Nothing         SubshellScope str -> return str+        _ -> Nothing     relevant t = isLoop t || isFunction t || isJust (subshellType t) checkLoopKeywordScope _ _ = return () @@ -2793,17 +2989,6 @@   -prop_checkStderrPipe1 = verify checkStderrPipe "#!/bin/ksh\nfoo |& bar"-prop_checkStderrPipe2 = verifyNot checkStderrPipe "#!/bin/bash\nfoo |& bar"-checkStderrPipe params =-    case shellType params of-        Ksh -> match-        _ -> const $ return ()-  where-    match (T_Pipe id "|&") =-        err id 2118 "Ksh does not support |&. Use 2>&1 |."-    match _ = return ()- prop_checkUnpassedInFunctions1 = verifyTree checkUnpassedInFunctions "foo() { echo $1; }; foo" prop_checkUnpassedInFunctions2 = verifyNotTree checkUnpassedInFunctions "foo() { echo $1; };" prop_checkUnpassedInFunctions3 = verifyNotTree checkUnpassedInFunctions "foo() { echo $lol; }; foo"@@ -2818,6 +3003,10 @@ prop_checkUnpassedInFunctions12 = verifyNotTree checkUnpassedInFunctions "foo() { echo ${!var*}; }; foo;" prop_checkUnpassedInFunctions13 = verifyNotTree checkUnpassedInFunctions "# shellcheck disable=SC2120\nfoo() { echo $1; }\nfoo\n" prop_checkUnpassedInFunctions14 = verifyTree checkUnpassedInFunctions "foo() { echo $#; }; foo"+prop_checkUnpassedInFunctions15 = verifyNotTree checkUnpassedInFunctions "foo() { echo ${1-x}; }; foo"+prop_checkUnpassedInFunctions16 = verifyNotTree checkUnpassedInFunctions "foo() { echo ${1:-x}; }; foo"+prop_checkUnpassedInFunctions17 = verifyNotTree checkUnpassedInFunctions "foo() { mycommand ${1+--verbose}; }; foo"+prop_checkUnpassedInFunctions18 = verifyNotTree checkUnpassedInFunctions "foo() { if mycheck; then foo ${1?Missing}; fi; }; foo" checkUnpassedInFunctions params root =     execWriter $ mapM_ warnForGroup referenceGroups   where@@ -2834,9 +3023,10 @@         case x of             Assignment (_, _, str, _) -> isPositional str             _ -> False+     isPositionalReference function x =         case x of-            Reference (_, t, str) -> isPositional str && t `isDirectChildOf` function+            Reference (_, t, str) -> isPositional str && t `isDirectChildOf` function && not (hasDefaultValue t)             _ -> False      isDirectChildOf child parent = fromMaybe False $ do@@ -2850,6 +3040,7 @@     referenceList :: [(String, Bool, Token)]     referenceList = execWriter $         doAnalysis (sequence_ . checkCommand) root+     checkCommand :: Token -> Maybe (Writer [(String, Bool, Token)] ())     checkCommand t@(T_SimpleCommand _ _ (cmd:args)) = do         str <- getLiteralString cmd@@ -2860,6 +3051,22 @@     isPositional str = str == "*" || str == "@" || str == "#"         || (all isDigit str && str /= "0" && str /= "") +    -- True if t is a variable that specifies a default value,+    -- such as ${1-x} or ${1:-x}.+    hasDefaultValue t =+        case t of+            T_DollarBraced _ True l ->+                let str = concat $ oversimplify l+                in isDefaultValueModifier $ getBracedModifier str+            _ -> False++    isDefaultValueModifier str =+        case str of+            ':':c:_ -> c `elem` handlesDefault+            c:_ -> c `elem` handlesDefault+            _ -> False+      where handlesDefault = "-+?"+     isArgumentless (_, b, _) = b     referenceGroups = Map.elems $ foldr updateWith Map.empty referenceList     updateWith x@(name, _, _) = Map.insertWith (++) name [x]@@ -2906,14 +3113,17 @@ prop_checkTildeInPath1 = verify checkTildeInPath "PATH=\"$PATH:~/bin\"" prop_checkTildeInPath2 = verify checkTildeInPath "PATH='~foo/bin'" prop_checkTildeInPath3 = verifyNot checkTildeInPath "PATH=~/bin"-checkTildeInPath _ (T_SimpleCommand _ vars _) =-    mapM_ checkVar vars+prop_checkTildeInPath4 = verify checkTildeInPath "export PATH=\"$PATH:~/b\""+prop_checkTildeInPath5 = verify checkTildeInPath "export PATH=$PATH:\"~/c\""+prop_checkTildeInPath6 = verify checkTildeInPath "declare -x PATH=\"$PATH:~/d\""+prop_checkTildeInPath7 = verify checkTildeInPath "typeset -x PATH=\"$PATH:~/e\""+prop_checkTildeInPath8 = verify checkTildeInPath "f() { local PATH=\"$PATH:~/f\"; }"+-- Match T_Assignment directly so PATH=… args of export/declare/typeset/local+-- are covered, not only prefix assignments on a simple command.+checkTildeInPath _ (T_Assignment id Assign "PATH" [] (T_NormalWord _ parts))+    | any (\x -> isQuoted x && hasTilde x) parts =+        warn id 2147 "Literal tilde in PATH works poorly across programs."   where-    checkVar (T_Assignment id Assign "PATH" [] (T_NormalWord _ parts))-        | any (\x -> isQuoted x && hasTilde x) parts =-            warn id 2147 "Literal tilde in PATH works poorly across programs."-    checkVar _ = return ()-     hasTilde t = '~' `elem` onlyLiteralString t     isQuoted T_DoubleQuoted {} = True     isQuoted T_SingleQuoted {} = True@@ -2922,7 +3132,8 @@  prop_checkUnsupported3 = verify checkUnsupported "#!/bin/sh\ncase foo in bar) baz ;& esac" prop_checkUnsupported4 = verify checkUnsupported "#!/bin/ksh\ncase foo in bar) baz ;;& esac"-prop_checkUnsupported5 = verify checkUnsupported "#!/bin/bash\necho \"${ ls; }\""+prop_checkUnsupported5 = verifyNot checkUnsupported "#!/bin/bash\necho \"${ ls; }\""+prop_checkUnsupported6 = verify checkUnsupported "#!/bin/ash\necho \"${ ls; }\"" checkUnsupported params t =     unless (null support || (shellType params `elem` support)) $         report name@@ -2936,7 +3147,7 @@ shellSupport t =   case t of     T_CaseExpression _ _ list -> forCase (map (\(a,_,_) -> a) list)-    T_DollarBraceCommandExpansion {} -> ("${ ..; } command expansion", [Ksh])+    T_DollarBraceCommandExpansion {} -> ("${ ..; } command expansion", [Bash, Ksh])     _ -> ("", [])   where     forCase seps | CaseContinue `elem` seps = ("cases with ;;&", [Bash])@@ -3024,7 +3235,7 @@             T_DollarExpansion _ [x] -> getPipeline x             T_Pipeline _ _ cmds -> return cmds             _ -> fail "unknown"-    isGrep = (`elem` ["grep", "egrep", "fgrep", "zgrep"])+    isGrep = (`elem` ["grep", "egrep", "fgrep", "bz3grep", "bzgrep", "xzgrep", "zgrep", "zipgrep", "zstdgrep"])  prop_checkTestArgumentSplitting1 = verify checkTestArgumentSplitting "[ -e *.mp3 ]" prop_checkTestArgumentSplitting2 = verifyNot checkTestArgumentSplitting "[[ $a == *b* ]]"@@ -3144,6 +3355,17 @@  checkReadWithoutR _ _ = return () +prop_checkCpLegacyR1 = verify checkCpLegacyR "cp -r foo bar"+prop_checkCpLegacyR2 = verifyNot checkCpLegacyR "cp -R foo bar"+checkCpLegacyR params t@T_SimpleCommand {} | t `isUnqualifiedCommand` "cp" = case legacyFlag of+  Just (t, _) -> warnWithFix (getId t) 2336 "cp -r behavior is implementation-defined"+                     (fixWith [replaceToken (getId t) params "-R"])+  Nothing -> return ()+  where+    flags = getAllFlags t+    legacyFlag = find ((=="r") . snd) flags+checkCpLegacyR _ _ = return ()+ prop_checkUncheckedCd1 = verifyTree checkUncheckedCdPushdPopd "cd ~/src; rm -r foo" prop_checkUncheckedCd2 = verifyNotTree checkUncheckedCdPushdPopd "cd ~/src || exit; rm -r foo" prop_checkUncheckedCd3 = verifyNotTree checkUncheckedCdPushdPopd "set -e; cd ~/src; rm -r foo"@@ -3175,9 +3397,17 @@ prop_checkUncheckedPopd11 = verifyNotTree checkUncheckedCdPushdPopd "cd ../.././.." prop_checkUncheckedPopd12 = verifyNotTree checkUncheckedCdPushdPopd "cd /" prop_checkUncheckedPopd13 = verifyTree checkUncheckedCdPushdPopd "cd ../../.../.."+prop_checkUncheckedCdInFunction1 = verifyNotTree checkUncheckedCdPushdPopd "#!/bin/bash\nfoo() {\n  cd /abc\n}"+prop_checkUncheckedCdInFunction2 = verifyNotTree checkUncheckedCdPushdPopd "foo() { cd /abc; return; }"+prop_checkUncheckedCdInFunction3 = verifyNotTree checkUncheckedCdPushdPopd "foo() { cd /abc; exit; }"+prop_checkUncheckedCdInFunction4 = verifyTree checkUncheckedCdPushdPopd "foo() { cd /abc; return 0; }"+prop_checkUncheckedCdInFunction5 = verifyTree checkUncheckedCdPushdPopd "foo() { cd /abc; return > output; }"+prop_checkUncheckedCdInFunction6 = verifyTree checkUncheckedCdPushdPopd "foo() { cd /abc; return | cat; }"+prop_checkUncheckedCdInFunction7 = verifyNotTree checkUncheckedCdPushdPopd "foo() { cd /abc; return $?; }"+prop_checkUncheckedCdInFunction8 = verifyNotTree checkUncheckedCdPushdPopd "foo() { cd /abc; exit $?; }"  checkUncheckedCdPushdPopd params root =-    if hasSetE params then+    if hasErrexit params then         []     else execWriter $ doAnalysis checkElement root   where@@ -3185,6 +3415,7 @@         | name `elem` ["cd", "pushd", "popd"]             && not (isSafeDir t)             && not (name `elem` ["pushd", "popd"] && ("n" `elem` map snd (getAllFlags t)))+            && not (isLastCommandInFunction t)             && not (isCondition $ getPath (parentMap params) t) =                 warnWithFix (getId t) 2164                     ("Use '" ++ name ++ " ... || exit' or '" ++ name ++ " ... || return' in case " ++ name ++ " fails.")@@ -3192,6 +3423,20 @@         where name = getName t     checkElement _ = return ()     getName t = fromMaybe "" $ getCommandName t+    isLastCommandInFunction t =+        go $ NE.tail $ getPath (parentMap params) t+      where+        go (child:T_BraceGroup _ commands:T_Function {}:_) =+            case dropWhile ((/= getId child) . getId) commands of+                [_] -> True+                [_, T_Pipeline _ [] [T_Redirecting _ [] (T_SimpleCommand _ [] (cmd:args))]] ->+                    getLiteralString cmd `elem` [Just "return", Just "exit"] && case args of+                        [] -> True+                        [T_NormalWord _ [T_DollarBraced _ False status]] -> getLiteralString status == Just "?"+                        _ -> False+                _ -> False+        go (_:rest) = go rest+        go [] = False     isSafeDir t = case oversimplify t of           [_, str] -> str `matches` regex           _ -> False@@ -3297,7 +3542,7 @@             next@(TA_Unary _ "!" _):_ -> isOnlyTestInCommand next             next@(TC_Group {}):_ -> isOnlyTestInCommand next             next@(TA_Sequence _ [_]):_ -> isOnlyTestInCommand next-            next@(TA_Parentesis _ _):_ -> isOnlyTestInCommand next+            next@(TA_Parenthesis _ _):_ -> isOnlyTestInCommand next             _ -> False      -- TODO: Do better $? tracking and filter on whether@@ -3516,7 +3761,7 @@         _ -> return ()     checkPart part = case part of         T_DollarExpansion id _ -> forCommand id-        T_DollarBraceCommandExpansion id _ -> forCommand id+        T_DollarBraceCommandExpansion id _ _ -> forCommand id         T_Backticked id _ -> forCommand id         T_DollarBraced id _ str |             not (isCountingReference part)@@ -3592,6 +3837,8 @@ prop_checkPipeToNowhere18 = verifyNot checkPipeToNowhere "ls 1>&3 3>&1 3>&- | wc -l" prop_checkPipeToNowhere19 = verifyNot checkPipeToNowhere "find . -print0 | du --files0-from=/dev/stdin" prop_checkPipeToNowhere20 = verifyNot checkPipeToNowhere "find . | du --exclude-from=/dev/fd/0"+prop_checkPipeToNowhere21 = verifyNot checkPipeToNowhere "yes | cp -ri foo/* bar"+prop_checkPipeToNowhere22 = verifyNot checkPipeToNowhere "yes | rm --interactive *"  data PipeType = StdoutPipe | StdoutStderrPipe | NoPipe deriving (Eq) checkPipeToNowhere :: Parameters -> Token -> WriterT [TokenComment] Identity ()@@ -3657,6 +3904,7 @@     commandSpecificException name cmd =         case name of             "du" -> any ((`elem` ["exclude-from", "files0-from"]) . snd) $ getAllFlags cmd+            _ | name `elem` interactiveFlagCmds -> hasInteractiveFlag cmd             _ -> False      warnAboutDupes (n, list@(_:_:_)) =@@ -3680,7 +3928,7 @@         name <- getCommandBasename cmd         guard $ name `elem` nonReadingCommands         guard . not $ hasAdditionalConsumers cmd-        guard . not $ name `elem` ["cp", "mv", "rm"] && cmd `hasFlag` "i"+        guard . not $ name `elem` interactiveFlagCmds && hasInteractiveFlag cmd         let suggestion =                 if name == "echo"                 then "Did you want 'cat' instead?"@@ -3695,6 +3943,9 @@     treeContains pred t = isNothing $         doAnalysis (guard . not . pred) t +    interactiveFlagCmds = [ "cp", "mv", "rm" ]+    hasInteractiveFlag cmd = cmd `hasFlag` "i" || cmd `hasFlag` "interactive"+     mayConsume t =         case t of             T_ProcSub _ "<" _ -> True@@ -3761,32 +4012,49 @@ prop_checkUseBeforeDefinition2 = verifyNotTree checkUseBeforeDefinition "f() { true; }; f" prop_checkUseBeforeDefinition3 = verifyNotTree checkUseBeforeDefinition "if ! mycmd --version; then mycmd() { true; }; fi" prop_checkUseBeforeDefinition4 = verifyNotTree checkUseBeforeDefinition "mycmd || mycmd() { f; }"-checkUseBeforeDefinition _ t =-    execWriter $ evalStateT (mapM_ examine $ revCommands) Map.empty+prop_checkUseBeforeDefinition5 = verifyTree checkUseBeforeDefinition "false || mycmd; mycmd() { f; }"+prop_checkUseBeforeDefinition6 = verifyNotTree checkUseBeforeDefinition "f() { one; }; f; f() { two; }; f"+prop_checkUseBeforeDefinition7 = verifyNotTree checkUseBeforeDefinition "f() { true; }\nreturn\necho \"$(f)\"\necho \"$(f)\""+prop_checkUseBeforeDefinition8 = verifyNotTree checkUseBeforeDefinition "#!/usr/bin/env bats\n@test 'foo' { f; }\nf() { true; }"+prop_checkUseBeforeDefinition9 = verifyNotTree checkUseBeforeDefinition "#!/usr/bin/env bats\n@test 'foo' { f; }\nsetup() { f() { true; }; }"+prop_checkUseBeforeDefinition10 = verifyTree checkUseBeforeDefinition "#!/usr/bin/env bats\n@test 'foo' {\n f\n f() { true; }\n}"+prop_checkUseBeforeDefinition11 = verifyTree checkUseBeforeDefinition "#!/usr/bin/env bats\nf\n@test 'foo' { true; }\nf() { true; }"+prop_checkUseBeforeDefinition12 = verifyNotTree checkUseBeforeDefinition "setup() { f() { true; }; }; f; f() { true; }"+prop_checkUseBeforeDefinition13 = verifyNotTree checkUseBeforeDefinition "#!/usr/bin/env bats\nsetup() { f() { true; }; }\n@test \"a\" {\n  f\n}\n@test \"b\" {\n  f() { true; }\n}"+checkUseBeforeDefinition :: Parameters -> Token -> [TokenComment]+checkUseBeforeDefinition params t = fromMaybe [] $ do+    cfga <- cfgAnalysis params+    let funcs = execState (doAnalysis findFunction t) Map.empty+    -- Green cut: no point enumerating commands if there are no functions.+    guard . not $ Map.null funcs+    return $ execWriter $ doAnalysis (findInvocation cfga funcs) t   where-    examine t = case t of-        T_Pipeline _ _ [T_Redirecting _ _ (T_Function _ _ _ name _)] ->-            modify $ Map.insert name t-        T_Annotation _ _ w -> examine w-        T_Pipeline _ _ cmds -> do-            m <- get-            unless (Map.null m) $-                mapM_ (checkUsage m) $ concatMap recursiveSequences cmds-        _ -> return ()+    findFunction t =+        case t of+            T_Function id _ _ name _ -> modify (Map.insertWith (++) name [(id, isInBatsTest t)])+            _ -> return () -    checkUsage map cmd = sequence_ $ do-        name <- getCommandName cmd-        def <- Map.lookup name map-        return $-            err (getId cmd) 2218-                "This function is only defined later. Move the definition up."+    isInBatsTest t = any isBatsTest $ getPath (parentMap params) t+    isBatsTest t = case t of T_BatsTest {} -> True; _ -> False -    revCommands = reverse $ concat $ getCommandSequences t-    recursiveSequences x =-        let list = concat $ getCommandSequences x in-            if null list-            then [x]-            else concatMap recursiveSequences list+    findInvocation cfga funcs t =+        case t of+            T_SimpleCommand id _ (cmd:_) -> sequence_ $ do+                name <- getLiteralString cmd+                definitions <- Map.lookup name funcs+                let invocations = map fst definitions+                -- Bats loads the whole file before running a test, so functions+                -- defined outside of tests are available in all of them.+                guard . not $ isInBatsTest t && any (not . snd) definitions+                -- Is the function definitely being defined later?+                -- Every definition has to be later: one whose order we can't+                -- determine, such as in a function nothing visibly invokes,+                -- may already have run.+                guard $ all (\c -> CF.doesPostDominate cfga c id) invocations+                -- Was one already defined, so it's actually a re-definition?+                guard . not $ any (\c -> CF.doesPostDominate cfga id c) invocations+                return $ err id 2218 "This function is only defined later. Move the definition up."+            _ -> return ()  prop_checkForLoopGlobVariables1 = verify checkForLoopGlobVariables "for i in $var/*.txt; do true; done" prop_checkForLoopGlobVariables2 = verifyNot checkForLoopGlobVariables "for i in \"$var\"/*.txt; do true; done"@@ -3890,12 +4158,22 @@             T_Annotation {} -> True             _ -> False -prop_checkInvertedStringTest1 = verify checkInvertedStringTest "[ ! -z $var ]"-prop_checkInvertedStringTest2 = verify checkInvertedStringTest "! [[ -n $var ]]"-prop_checkInvertedStringTest3 = verifyNot checkInvertedStringTest "! [ -x $var ]"-prop_checkInvertedStringTest4 = verifyNot checkInvertedStringTest "[[ ! -w $var ]]"-prop_checkInvertedStringTest5 = verifyNot checkInvertedStringTest "[ -z $var ]"-checkInvertedStringTest _ t =+prop_checkUnnecessarilyInvertedTest1 = verify checkUnnecessarilyInvertedTest "[ ! -z $var ]"+prop_checkUnnecessarilyInvertedTest2 = verify checkUnnecessarilyInvertedTest "! [[ -n $var ]]"+prop_checkUnnecessarilyInvertedTest3 = verifyNot checkUnnecessarilyInvertedTest "! [ -x $var ]"+prop_checkUnnecessarilyInvertedTest4 = verifyNot checkUnnecessarilyInvertedTest "[[ ! -w $var ]]"+prop_checkUnnecessarilyInvertedTest5 = verifyNot checkUnnecessarilyInvertedTest "[ -z $var ]"+prop_checkUnnecessarilyInvertedTest6 = verify checkUnnecessarilyInvertedTest "! [ $var != foo ]"+prop_checkUnnecessarilyInvertedTest7 = verify checkUnnecessarilyInvertedTest "[[ ! $var == foo ]]"+prop_checkUnnecessarilyInvertedTest8 = verifyNot checkUnnecessarilyInvertedTest "! [[ $var =~ .* ]]"+prop_checkUnnecessarilyInvertedTest9 = verify checkUnnecessarilyInvertedTest "[ ! $var -eq 0 ]"+prop_checkUnnecessarilyInvertedTest10 = verify checkUnnecessarilyInvertedTest "! [[ $var -gt 3 ]]"+prop_checkUnnecessarilyInvertedTest11 = verify checkUnnecessarilyInvertedTest "test ! -n \"$1\""+prop_checkUnnecessarilyInvertedTest12 = verify checkUnnecessarilyInvertedTest "! test -z \"$1\""+prop_checkUnnecessarilyInvertedTest13 = verifyNot checkUnnecessarilyInvertedTest "test ! -x \"$1\""+prop_checkUnnecessarilyInvertedTest14 = verifyNot checkUnnecessarilyInvertedTest "test -n \"$1\""+prop_checkUnnecessarilyInvertedTest15 = verifyNot checkUnnecessarilyInvertedTest "! test -x \"$1\""+checkUnnecessarilyInvertedTest _ t =     case t of         TC_Unary _ _ "!" (TC_Unary _ _ op _) ->             case op of@@ -3903,13 +4181,55 @@                 "-z" -> style (getId t) 2236 "Use -n instead of ! -z."                 _ -> return ()         T_Banged _ (T_Pipeline _ _-          [T_Redirecting _ _ (T_Condition _ _ (TC_Unary _ _ op _))]) ->+          [T_Redirecting _ _ (T_Condition _ _ _ (TC_Unary _ _ op _))]) ->             case op of                 "-n" -> style (getId t) 2237 "Use [ -z .. ] instead of ! [ -n .. ]."                 "-z" -> style (getId t) 2237 "Use [ -n .. ] instead of ! [ -z .. ]."                 _ -> return ()+        -- test ! -n x+        T_SimpleCommand _ _ [_, bang, op, _]+          | t `isCommand` "test" && getLiteralString bang == Just "!" ->+            case getLiteralString op of+                Just "-n" -> style (getId t) 2236 "Use -z instead of ! -n."+                Just "-z" -> style (getId t) 2236 "Use -n instead of ! -z."+                _ -> return ()+        -- ! test -z x+        T_Banged _ (T_Pipeline _ _+          [T_Redirecting _ _ s@(T_SimpleCommand _ _ [_, op, _])])+          | s `isCommand` "test" ->+            case getLiteralString op of+                Just "-n" -> style (getId t) 2237 "Use test -z .. instead of ! test -n .."+                Just "-z" -> style (getId t) 2237 "Use test -n .. instead of ! test -z .."+                _ -> return ()+        TC_Unary _ _ "!" (TC_Binary _ bracketStyle op _ _) ->+            maybeSuggestRewrite True bracketStyle (getId t) op+        T_Banged _ (T_Pipeline _ _+          [T_Redirecting _ _ (T_Condition _ _ _ (TC_Binary _ bracketStyle op _ _))]) ->+            maybeSuggestRewrite False bracketStyle (getId t) op         _ -> return ()+  where+    inversionMap = Map.fromList [+        ("=",  "!="),+        ("==", "!="),+        ("!=", "="),+        ("-eq", "-ne"),+        ("-ne", "-eq"),+        ("-le", "-gt"),+        ("-gt", "-le"),+        ("-ge", "-lt"),+        ("-lt", "-ge")+      ]+    maybeSuggestRewrite bangInside bracketStyle id op = sequence_ $ do+        newOp <- Map.lookup op inversionMap+        let oldExpr = "a " ++ op ++ " b"+        let newExpr = "a " ++ newOp ++ " b"+        let bracket s = if bracketStyle == SingleBracket then "[ " ++ s ++ " ]" else "[[ " ++ s ++ " ]]"+        return $+            if bangInside+                then style id 2335 $ "Use " ++ newExpr ++ " instead of ! " ++ oldExpr ++ "."+                else style id 2335 $ "Use " ++ (bracket newExpr) ++ " instead of ! " ++ (bracket oldExpr) ++ "." + prop_checkRedirectionToCommand1 = verify checkRedirectionToCommand "ls > rm" prop_checkRedirectionToCommand2 = verifyNot checkRedirectionToCommand "ls > 'rm'" prop_checkRedirectionToCommand3 = verifyNot checkRedirectionToCommand "ls > myfile"@@ -3962,13 +4282,10 @@ prop_checkTranslatedStringVariable5 = verifyNot checkTranslatedStringVariable "foo=var; bar=val2; $\"foo bar\"" checkTranslatedStringVariable params (T_DollarDoubleQuoted id [T_Literal _ s])   | all isVariableChar s-  && Map.member s assignments+  && S.member s assignments   = warnWithFix id 2256 "This translated string is the name of a variable. Flip leading $ and \" if this should be a quoted substitution." (fix id)   where-    assignments = foldl (flip ($)) Map.empty (map insertAssignment $ variableFlow params)-    insertAssignment (Assignment (_, token, name, _)) | isVariableName name =-        Map.insert name token-    insertAssignment _ = Prelude.id+    assignments = S.fromList [name | Assignment (_, _, name, _) <- variableFlow params, isVariableName name]     fix id = fixWith [replaceStart id params 2 "\"$"] checkTranslatedStringVariable _ _ = return () @@ -3998,7 +4315,8 @@ prop_checkUselessBang7 = verifyNot checkUselessBang "set -e; x() { ! [ x ]; }" prop_checkUselessBang8 = verifyNot checkUselessBang "set -e; if { ! true; }; then true; fi" prop_checkUselessBang9 = verifyNot checkUselessBang "set -e; while ! true; do true; done"-checkUselessBang params t = when (hasSetE params) $ mapM_ check (getNonReturningCommands t)+prop_checkUselessBang10 = verify checkUselessBang "set -e\nshellcheck disable=SC0000\n! true\nrest"+checkUselessBang params t = when (hasErrexit params) $ mapM_ check (getNonReturningCommands t)   where     check t =         case t of@@ -4006,6 +4324,7 @@                 addComment $ makeCommentWithFix InfoC id 2251                         "This ! is not on a condition and skips errexit. Use `&& exit 1` instead, or make sure $? is checked."                         (fixWith [replaceStart id params 1 "", replaceEnd (getId cmd) params 0 " && exit 1"])+            T_Annotation _ _ t -> check t             _ -> return ()      -- Get all the subcommands that aren't likely to be the return value@@ -4165,6 +4484,7 @@     checkList name t =         case t of             T_Backgrounded _ t -> checkList name t+            T_KshCoprocess _ t -> checkList name t             T_AndIf _ lhs _ -> checkList name lhs             T_OrIf _ lhs _ -> checkList name lhs             T_Pipeline _ _ cmds -> mapM_ (checkCommand name) cmds@@ -4196,7 +4516,7 @@         in             mapM_ checkTest commandWithSeps     checkTest (before, cmd, after) =-        when (isTest cmd) $ do+        when (isTestCommand cmd) $ do             checkPipe before             checkPipe after @@ -4212,17 +4532,10 @@             T_AndIf _ _ rhs -> checkAnds id rhs             T_OrIf _ _ rhs -> checkAnds id rhs             T_Pipeline _ _ list | not (null list) -> checkAnds id (last list)-            cmd -> when (isTest cmd) $+            cmd -> when (isTestCommand cmd) $                 errWithFix id 2265 "Use && for logical AND. Single & will background and return true." $                     (fixWith [replaceEnd id params 0 "&"]) -    isTest t =-        case t of-            T_Condition {} -> True-            T_SimpleCommand {} -> t `isCommand` "test"-            T_Redirecting _ _ t -> isTest t-            T_Annotation _ _ t -> isTest t-            _ -> False  prop_checkComparisonWithLeadingX1 = verify checkComparisonWithLeadingX "[ x$foo = xlol ]" prop_checkComparisonWithLeadingX2 = verify checkComparisonWithLeadingX "test x$foo = xlol"@@ -4230,14 +4543,16 @@ prop_checkComparisonWithLeadingX4 = verifyNot checkComparisonWithLeadingX "test $foo = xbar" prop_checkComparisonWithLeadingX5 = verify checkComparisonWithLeadingX "[ \"x$foo\" = 'xlol' ]" prop_checkComparisonWithLeadingX6 = verify checkComparisonWithLeadingX "[ x\"$foo\" = x'lol' ]"+prop_checkComparisonWithLeadingX7 = verify checkComparisonWithLeadingX "[ X$foo != Xbar ]" checkComparisonWithLeadingX params t =     case t of-        TC_Binary id typ op lhs rhs | op == "=" || op == "==" ->-            check lhs rhs-        T_SimpleCommand _ _ [cmd, lhs, op, rhs] |-            getLiteralString cmd == Just "test" &&-                getLiteralString op `elem` [Just "=", Just "=="] ->-                    check lhs rhs+        TC_Binary id typ op lhs rhs+            | op `elem` ["=", "==", "!="] ->+                check lhs rhs+        T_SimpleCommand _ _ [cmd, lhs, op, rhs]+            | getLiteralString cmd == Just "test" &&+              getLiteralString op `elem` [Just "=", Just "==", Just "!="] ->+                check lhs rhs         _ -> return ()   where     msg = "Avoid x-prefix in comparisons as it no longer serves a purpose."@@ -4247,19 +4562,20 @@         return $ styleWithFix (getId lhs) 2268 msg $ fixWith [l, r]      fixLeadingX token =-         case getWordParts token of-            T_Literal id ('x':_):_ ->+        case getWordParts token of+            T_Literal id (c:_):_ | toLower c == 'x' ->                 case token of-                    -- The side is a single, unquoted x, so we have to quote-                    T_NormalWord _ [T_Literal id "x"] ->+                    -- The side is a single, unquoted x or X, so we have to quote+                    T_NormalWord _ [T_Literal id [c]] ->                         return $ replaceStart id params 1 "\"\""                     -- Otherwise we can just delete it                     _ -> return $ replaceStart id params 1 ""-            T_SingleQuoted id ('x':_):_ ->-                -- Replace the single quote and x-                return $ replaceStart id params 2 "'"+            T_SingleQuoted id (c:rest):_ | toLower c == 'x' ->+                    -- Replace the single quote and the character x or X+                    return $ replaceStart id params 2 "'"             _ -> Nothing + prop_checkAssignToSelf1 = verify checkAssignToSelf "x=$x" prop_checkAssignToSelf2 = verify checkAssignToSelf "x=${x}" prop_checkAssignToSelf3 = verify checkAssignToSelf "x=\"$x\""@@ -4537,35 +4853,56 @@ prop_checkRequireDoubleBracket2 = verifyTree checkRequireDoubleBracket "[ foo -o bar ]" prop_checkRequireDoubleBracket3 = verifyNotTree checkRequireDoubleBracket "#!/bin/sh\n[ -x foo ]" prop_checkRequireDoubleBracket4 = verifyNotTree checkRequireDoubleBracket "[[ -x foo ]]"+prop_checkRequireDoubleBracket5 = verifyTreeFix checkRequireDoubleBracket "[ -x foo ]" "[[ -x foo ]]"+prop_checkRequireDoubleBracket6 = verifyTreeFix checkRequireDoubleBracket "[ -x foo ]]" "[[ -x foo ]]" checkRequireDoubleBracket params =-    if isBashLike params+    if (shellType params) `elem` [Bash, Ksh, BusyboxSh]     then nodeChecksToTreeCheck [check] params     else const []   where     check _ t = case t of-        T_Condition id SingleBracket _ ->-            styleWithFix id 2292 "Prefer [[ ]] over [ ] for tests in Bash/Ksh." (fixFor t)+        T_Condition id SingleBracket _ _ ->+            styleWithFix id 2292 "Prefer [[ ]] over [ ] for tests in Bash/Ksh/Busybox." (fixFor t)         _ -> return ()      fixFor t = fixWith $         if isSimple t         then-            [-                replaceStart (getId t) params 0 "[",-                replaceEnd (getId t) params 0 "]"-            ]+            replaceStart (getId t) params 0 "[" :+                -- Don't add another ] if it was (wrongly) closed with ]] already+                [ replaceEnd (getId t) params 0 "]" | not $ isClosedWithDouble t ]         else [] +    isClosedWithDouble t = case t of+        T_Condition _ _ DoubleBracket _ -> True+        _ -> False+     -- We don't tag operators like < and -o well enough to replace them,     -- so just handle the simple cases.     isSimple t = case t of-        T_Condition _ _ s -> isSimple s+        T_Condition _ _ _ s -> isSimple s         TC_Binary _ _ op _ _ -> not $ any (\x -> x `elem` op) "<>"         TC_Unary {} -> True         TC_Nullary {} -> True         _ -> False  +prop_checkRequireDoubleEquals1 = verifyTree checkRequireDoubleEquals "[[ \"$x\" = \"$y\" ]]"+prop_checkRequireDoubleEquals2 = verifyTree checkRequireDoubleEquals "[ \"$x\" = \"$y\" ]"+prop_checkRequireDoubleEquals3 = verifyNotTree checkRequireDoubleEquals "[[ \"$x\" == \"$y\" ]]"+prop_checkRequireDoubleEquals4 = verifyNotTree checkRequireDoubleEquals "#!/bin/sh\n[ \"$x\" = \"$y\" ]"+prop_checkRequireDoubleEquals5 = verifyNotTree checkRequireDoubleEquals "#!/bin/ksh\n[[ \"$x\" = \"$y\" ]]"+checkRequireDoubleEquals params =+    if shellType params == Bash+    then nodeChecksToTreeCheck [check] params+    else const []+  where+    check _ t = case t of+        TC_Binary id _ "=" _ _ ->+            style id 2338 "Prefer == over = for string comparisons in Bash tests."+        _ -> return ()++ prop_checkUnquotedParameterExpansionPattern1 = verify checkUnquotedParameterExpansionPattern  "echo \"${var#$x}\"" prop_checkUnquotedParameterExpansionPattern2 = verify checkUnquotedParameterExpansionPattern  "echo \"${var%%$(x)}\"" prop_checkUnquotedParameterExpansionPattern3 = verifyNot checkUnquotedParameterExpansionPattern  "echo \"${var[#$x]}\""@@ -4695,8 +5032,18 @@ prop_checkSetESuppressed17 = verifyNotTree checkSetESuppressed "set -e; f(){ :; }; g(){ :; }; g f" prop_checkSetESuppressed18 = verifyNotTree checkSetESuppressed "set -e; shopt -s inherit_errexit; f(){ :; }; x=$(f)" prop_checkSetESuppressed19 = verifyNotTree checkSetESuppressed "set -e; set -o posix; f(){ :; }; x=$(f)"+prop_checkSetESuppressed20 = verifyTree    checkSetESuppressed "set -e; set -o pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed21 = verifyTree    checkSetESuppressed "set -e; set +o inherit_errexit; f(){ :; }; x=$(f)"+prop_checkSetESuppressed22 = verifyTree    checkSetESuppressed "set -e; set -o vi; f(){ :; }; x=$(f)"+prop_checkSetESuppressed23 = verifyTree    checkSetESuppressed "set -e; set -o noglob; f(){ :; }; x=$(f)"+prop_checkSetESuppressed24 = verifyNotTree checkSetESuppressed "set -e; shopt -s inherit_errexit; set -o pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed24B = verifyNotTree checkSetESuppressed "builtin set -e; builtin shopt -s inherit_errexit; builtin set -o pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed25 = verifyTree    checkSetESuppressed "set -e; shopt -u inherit_errexit; set -o pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed26 = verifyTree    checkSetESuppressed "set -e; set -euo pipefail; f(){ :; }; x=$(f)"+prop_checkSetESuppressed27 = verifyTree    checkSetESuppressed "builtin set -e; builtin set -euo pipefail; f(){ :; }; x=$(f)"+ checkSetESuppressed params t =-    if hasSetE params then runNodeAnalysis checkNode params t else []+    if hasErrexit params then runNodeAnalysis checkNode params t else []   where     checkNode _ (T_SimpleCommand _ _ (cmd:_)) = when (isFunction cmd) (checkCmd cmd)     checkNode _ _ = return ()@@ -4733,7 +5080,7 @@                 "Bash implicitly disabled set -e for this function " ++                 "invocation because it's inside a command substitution. " ++                 "Add set -e; before it or enable inherit_errexit.")-        errExitEnabled t = hasInheritErrexit params || containsSetE t+        errExitEnabled t = hasInheritErrexit params || containsErrexit t         isIn t cmds = getId t `elem` map getId cmds  @@ -4775,13 +5122,16 @@ prop_checkExtraMaskedReturns36 = verifyNotTree checkExtraMaskedReturns "time false" prop_checkExtraMaskedReturns37 = verifyNotTree checkExtraMaskedReturns "time $(time false)" prop_checkExtraMaskedReturns38 = verifyTree checkExtraMaskedReturns "x=$(time time time false) time $(time false)"+prop_checkExtraMaskedReturns39 = verifyNotTree checkExtraMaskedReturns "eval \"$(false || echo exit 42)\""+prop_checkExtraMaskedReturns40 = verifyNotTree checkExtraMaskedReturns "eval \"$(git rev-parse --parseopt -- \"$@\" || echo exit $?)\""+prop_checkExtraMaskedReturns41 = verifyTree checkExtraMaskedReturns "true \"$(false || cat)\""  checkExtraMaskedReturns params t =     runNodeAnalysis findMaskingNodes params (removeTransparentCommands t)   where     findMaskingNodes _ (T_Arithmetic _ list) = findMaskedNodesInList [list]     findMaskingNodes _ (T_Array _ list) = findMaskedNodesInList $ allButLastSimpleCommands list-    findMaskingNodes _ (T_Condition _ _ condition) = findMaskedNodesInList [condition]+    findMaskingNodes _ (T_Condition _ _ _ condition) = findMaskedNodesInList [condition]     findMaskingNodes _ (T_DoubleQuoted _ list) = findMaskedNodesInList $ allButLastSimpleCommands list     findMaskingNodes _ (T_HereDoc _ _ _ _ list) = findMaskedNodesInList list     findMaskingNodes _ (T_HereString _ word) = findMaskedNodesInList [word]@@ -4824,7 +5174,7 @@     isMaskDeliberate t = any isOrIf $ NE.init $ parents params t       where         isOrIf (T_OrIf _ _ (T_Pipeline _ _ [T_Redirecting _ _ cmd]))-            = getCommandBasename cmd `elem` [Just "true", Just ":"]+            = getCommandBasename cmd `elem` [Just "true", Just ":", Just "echo"]         isOrIf _ = False      isCheckedElsewhere t = any isDeclaringCommand $ NE.tail $ parents params t@@ -4874,7 +5224,7 @@   where     check commands t =         case t of-            T_Banged id (T_Pipeline _ _ [T_Redirecting _ _ (T_Condition idCondition _ _)]) ->+            T_Banged id (T_Pipeline _ _ [T_Redirecting _ _ (T_Condition idCondition _ _ _)]) ->                                 if t `isLastOf` commands                                 then style id 2315 "In Bats, ! will not fail the test if it is not the last command anymore. Fold the `!` into the conditional!"                                 else err   id 2315 "In Bats, ! does not cause a test failure. Fold the `!` into the conditional!"@@ -4895,16 +5245,40 @@ prop_checkCommandIsUnreachable1 = verify checkCommandIsUnreachable "foo; bar; exit; baz" prop_checkCommandIsUnreachable2 = verify checkCommandIsUnreachable "die() { exit; }; foo; bar; die; baz" prop_checkCommandIsUnreachable3 = verifyNot checkCommandIsUnreachable "foo; bar || exit; baz"+prop_checkCommandIsUnreachable4 = verifyNot checkCommandIsUnreachable "f() { foo; };    # Maybe sourced"+prop_checkCommandIsUnreachable5 = verify checkCommandIsUnreachable "f() { foo; }; exit  # Not sourced"+prop_checkCommandIsUnreachable6 = verifyNot checkCommandIsUnreachable "f() { case x in *) : ;;& foo) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable7 = verify checkCommandIsUnreachable "f() { case x in *) return;; foo) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable8 = verify checkCommandIsUnreachable "f() { case x in foo) : ;;& *) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable9 = verifyNot checkCommandIsUnreachable "f() { case x in *) : ;;& foo) return;; bar) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable10 = verifyNot checkCommandIsUnreachable "f() { case x in *) : ;& foo) : ;;& bar) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable11 = verify checkCommandIsUnreachable "f() { case x in *) : ;& foo) return;; esac; echo x; }; f"+prop_checkCommandIsUnreachable12 = verifyNot checkCommandIsUnreachable "f() { case x in *) : ;;& foo) return;; *) :;; esac; echo x; }; f" checkCommandIsUnreachable params t =     case t of         T_Pipeline {} -> sequence_ $ do             cfga <- cfgAnalysis params-            state <- CF.getIncomingState cfga id+            state <- CF.getIncomingState cfga (getId t)             guard . not $ CF.stateIsReachable state             guard . not $ isSourced params t-            return $ info id 2317 "Command appears to be unreachable. Check usage (or ignore if invoked indirectly)."+            guard . not $ any (\t -> isUnreachable t || isUnreachableFunction t) $ NE.drop 1 $ getPath (parentMap params) t+            return $ info (getId t) 2317 "Command appears to be unreachable. Check usage (or ignore if invoked indirectly)."+        T_Function id _ _ _ _ ->+            when (isUnreachableFunction t+                    && (not . any isUnreachableFunction . NE.drop 1 $ getPath (parentMap params) t)+                    && (not $ isSourced params t)) $+                info id 2329 "This function is never invoked. Check usage (or ignored if invoked indirectly)."         _ -> return ()-  where id = getId t+  where+    isUnreachableFunction :: Token -> Bool+    isUnreachableFunction f =+        case f of+            T_Function id _ _ _ t -> isUnreachable t+            _ -> False+    isUnreachable t = fromMaybe False $ do+        cfga <- cfgAnalysis params+        state <- CF.getIncomingState cfga (getId t)+        return . not $ CF.stateIsReachable state   prop_checkOverwrittenExitCode1 = verify checkOverwrittenExitCode "x; [ $? -eq 1 ] || [ $? -eq 2 ]"@@ -4912,9 +5286,19 @@ prop_checkOverwrittenExitCode3 = verify checkOverwrittenExitCode "x; echo \"Exit is $?\"; [ $? -eq 0 ]" prop_checkOverwrittenExitCode4 = verifyNot checkOverwrittenExitCode "x; [ $? -eq 0 ] && echo Success" prop_checkOverwrittenExitCode5 = verify checkOverwrittenExitCode "x; if [ $? -eq 0 ]; then var=$?; fi"+prop_checkOverwrittenExitCode5a = verify checkOverwrittenExitCode "x; if [ $? -eq 0 ]; then exit $?; fi" prop_checkOverwrittenExitCode6 = verify checkOverwrittenExitCode "x; [ $? -gt 0 ] && fail=$?"+prop_checkOverwrittenExitCode6a = verify checkOverwrittenExitCode "x; [ $? -eq 0 ] && exit $?" prop_checkOverwrittenExitCode7 = verifyNot checkOverwrittenExitCode "[ 1 -eq 2 ]; status=$?" prop_checkOverwrittenExitCode8 = verifyNot checkOverwrittenExitCode "[ 1 -eq 2 ]; exit $?"+prop_checkOverwrittenExitCode9  = verifyNot checkOverwrittenExitCode "[[ -e \"./lockfile\" ]] || retval=$?"+prop_checkOverwrittenExitCode10 = verifyNot checkOverwrittenExitCode "[ -e \"./lockfile\" ] || retval=$?"+prop_checkOverwrittenExitCode11 = verifyNot checkOverwrittenExitCode "[ 1 -eq 2 ] && status=$?"+prop_checkOverwrittenExitCode12 = verify checkOverwrittenExitCode "x; printf '%d' $?; [ $? -eq 0 ]"+prop_checkOverwrittenExitCode13 = verifyNot checkOverwrittenExitCode "read -r x; [ $? -eq 0 ]"+prop_checkOverwrittenExitCode14 = verifyNot checkOverwrittenExitCode "x; echo $! > pid; [ $? -eq 0 ]"+prop_checkOverwrittenExitCode15 = verifyNot checkOverwrittenExitCode "x; printf \"%s\" \"$passwd\" >> /etc/passwd; [ $? -gt 0 ]"+prop_checkOverwrittenExitCode16 = verifyNot checkOverwrittenExitCode "x & echo $! > /var/something/pid; [ $? -eq 0 ] || ..." checkOverwrittenExitCode params t =     case t of         T_DollarBraced id _ val | getLiteralString val == Just "?" -> check id@@ -4928,10 +5312,16 @@          let idToToken = idMap params         exitCodeTokens <- traverse (\k -> Map.lookup k idToToken) $ S.toList exitCodeIds+        let inAssignment = isInAssignment id+            condHasDollarQ = conditionContainsDollarQuestion id exitCodeIds+            suppress = inAssignment && not condHasDollarQ         return $ do-            when (all isCondition exitCodeTokens && not (usedUnconditionally cfga t exitCodeIds)) $+            when (all isCondition exitCodeTokens+                  && not (usedUnconditionally cfga t exitCodeIds)+                  && not suppress) $                 warn id 2319 "This $? refers to a condition, not a command. Assign to a variable to avoid it being overwritten."-            when (all isPrinting exitCodeTokens) $+            when (all isPrinting exitCodeTokens+                  && not suppress) $                 warn id 2320 "This $? refers to echo/printf, not a previous command. Assign to variable to avoid it being overwritten."      isCondition t =@@ -4946,12 +5336,43 @@         all (\c -> CF.doesPostDominate cfga (getId t) c) testIds      isPrinting t =-        case getCommandBasename t of-            Just "echo" -> True-            Just "printf" -> True-            _ -> False+        if hasRedirection t == Just True+        then+            -- If the command writes somewhere, that's probably what the user wanted to check+            False+        else+            case getCommandBasename t of+                Just "echo" -> True+                Just "printf" -> True+                _ -> False +    hasRedirection :: Token -> Maybe Bool+    hasRedirection simpleCmd = do+        -- The CFG annotates exit statuses with their SimpleCommand, so we have to look up the surrounding Redircting:+        T_Redirecting _ list _ <- getClosestCommand (parentMap params) simpleCmd+        return . not . null $ list +    isInAssignment tokenId =+        let token = Map.lookup tokenId (idMap params)+        in maybe False (\tok -> any isAssignmentToken $ getPath (parentMap params) tok) token+      where+        isAssignmentToken (T_Assignment _ _ _ _ _) = True+        isAssignmentToken _ = False++    conditionContainsDollarQuestion tokenId exitIds =+        let tree = parentMap params+            tokenMap = idMap params+            condTokens = mapMaybe (`Map.lookup` tokenMap) (S.toList exitIds)+            dollarQTokens = [(tid, tok) | (tid, tok) <- Map.toList tokenMap,+                                           tid /= tokenId,+                                           isDollarQ tok]+            isDollarQ (T_DollarBraced _ _ val) = getLiteralString val == Just "?"+            isDollarQ _ = False+        in any (\(_, dqToken) ->+            any (\cond -> isParentOf tree cond dqToken) condTokens+          ) dollarQTokens++ prop_checkUnnecessaryArithmeticExpansionIndex1 = verify checkUnnecessaryArithmeticExpansionIndex "a[$((1+1))]=n" prop_checkUnnecessaryArithmeticExpansionIndex2 = verifyNot checkUnnecessaryArithmeticExpansionIndex "a[1+1]=n" prop_checkUnnecessaryArithmeticExpansionIndex3 = verifyNot checkUnnecessaryArithmeticExpansionIndex "a[$(echo $((1+1)))]=n"@@ -4984,14 +5405,14 @@         T_ForArithmetic _ x y z _ -> mapM_ (checkLeading "for (((x); (y); (z))) is the same as for ((x; y; z))")  [x,y,z]         T_Assignment _ _ _ [t] _ -> checkLeading "a[(x)] is the same as a[x]" t         T_Arithmetic _ t -> checkLeading "(( (x) )) is the same as (( x ))" t-        TA_Parentesis _ (TA_Sequence _ [ TA_Parentesis id _ ]) ->+        TA_Parenthesis _ (TA_Sequence _ [ TA_Parenthesis id _ ]) ->             styleWithFix id 2322 "In arithmetic contexts, ((x)) is the same as (x). Prefer only one layer of parentheses." $ fix id         _ -> return ()   where      checkLeading str t =         case t of-            TA_Sequence _ [TA_Parentesis id _ ] -> styleWithFix id 2323 (str ++ ". Prefer not wrapping in additional parentheses.") $ fix id+            TA_Sequence _ [TA_Parenthesis id _ ] -> styleWithFix id 2323 (str ++ ". Prefer not wrapping in additional parentheses.") $ fix id             _ -> return ()      fix id =@@ -5017,7 +5438,8 @@             state <- CF.getIncomingState cfga id             guard $ isNumber state word             guard . not $ fromMaybe False $ CF.variableMayBeDeclaredInteger state var-            return $ warn id 2324 "var+=1 will append, not increment. Use (( var += 1 )), declare -i var, or quote number to silence."+            -- Recommend "typeset" because ksh does not have "declare".+            return $ warn id 2324 "var+=1 will append, not increment. Use (( var += 1 )), typeset -i var, or quote number to silence."         _ -> return ()    where@@ -5038,6 +5460,54 @@         in             isUnquotedNumber || isNumericalVariableName || isNumericalVariableExpansion +++prop_checkExpansionWithRedirection1 = verify checkExpansionWithRedirection "var=$(foo > bar)"+prop_checkExpansionWithRedirection2 = verify checkExpansionWithRedirection "var=`foo 1> bar`"+prop_checkExpansionWithRedirection3 = verify checkExpansionWithRedirection "var=${ foo >> bar; }"+prop_checkExpansionWithRedirection4 = verify checkExpansionWithRedirection "var=$(foo | bar > baz)"+prop_checkExpansionWithRedirection5 = verifyNot checkExpansionWithRedirection "stderr=$(foo 2>&1 > /dev/null)"+prop_checkExpansionWithRedirection6 = verifyNot checkExpansionWithRedirection "var=$(foo; bar > baz)"+prop_checkExpansionWithRedirection7 = verifyNot checkExpansionWithRedirection "var=$(foo > bar; baz)"+prop_checkExpansionWithRedirection8 = verifyNot checkExpansionWithRedirection "var=$(cat <&3)"+checkExpansionWithRedirection params t =+    case t of+        T_DollarExpansion id [cmd] -> check id cmd+        T_Backticked id [cmd] -> check id cmd+        T_DollarBraceCommandExpansion id _ [cmd] -> check id cmd+        _ -> return ()+  where+    check id pipe =+        case pipe of+            (T_Pipeline _ _ t@(_:_)) -> checkCmd id (last t)+            _ -> return ()++    checkCmd captureId (T_Redirecting _ redirs _) = foldr (walk captureId) (return ()) redirs+    checkCmd _ _ = return ()++    walk captureId t acc =+        case t of+            T_FdRedirect _ _ (T_IoDuplicate _ _ "1") -> return ()+            T_FdRedirect id "1" (T_IoDuplicate _ _ _) -> return ()+            T_FdRedirect id "" (T_IoDuplicate _ op _) | op `elem` [T_GREATAND (Id 0), T_Greater (Id 0)] -> emit id captureId True+            T_FdRedirect id str (T_IoFile _ op file) | str `elem` ["", "1"] && op `elem` [ T_DGREAT (Id 0), T_Greater (Id 0) ]  ->+                emit id captureId $ getLiteralString file /= Just "/dev/null"+            _ -> acc++    emit redirectId captureId suggestTee = do+        warn captureId 2327 "This command substitution will be empty because the command's output gets redirected away."+        err redirectId 2328 $ "This redirection takes output away from the command substitution" ++ if suggestTee then " (use tee to duplicate)." else "."+++prop_checkUnaryTestA1 = verify checkUnaryTestA "[ -a foo ]"+prop_checkUnaryTestA2 = verify checkUnaryTestA "[ ! -a foo ]"+prop_checkUnaryTestA3 = verifyNot checkUnaryTestA "[ foo -a bar ]"+checkUnaryTestA params t =+    case t of+        TC_Unary id _ "-a" _ ->+            styleWithFix id 2331 "For file existence, prefer standard -e over legacy -a." $+                fixWith [replaceStart id params 2 "-e"]+        _ -> return ()  return [] runTests =  $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])
src/ShellCheck/AnalyzerLib.hs view
@@ -81,14 +81,20 @@ composeAnalyzers f g x = f x >> g x  data Parameters = Parameters {+    -- Whether this script has 'set -a' or 'set -o allexport' anywhere.+    hasAllexport       :: Bool,     -- Whether this script has the 'lastpipe' option set/default.     hasLastpipe        :: Bool,     -- Whether this script has the 'inherit_errexit' option set/default.     hasInheritErrexit  :: Bool,-    -- Whether this script has 'set -e' anywhere.-    hasSetE            :: Bool,+    -- Whether this script has 'set -e' or 'set -o errexit' anywhere.+    hasErrexit         :: Bool,+    -- Whether this script has 'set -f' or 'set -o noglob' anywhere.+    hasNoglob          :: Bool,     -- Whether this script has 'set -o pipefail' anywhere.     hasPipefail        :: Bool,+    -- Whether this script has 'shopt -s execfail' anywhere.+    hasExecfail        :: Bool,     -- A linear (bad) analysis of data flow     variableFlow       :: [StackData],     -- A map from Id to Token@@ -110,7 +116,7 @@ -- TODO: Cache results of common AST ops here data Cache = Cache {} -data Scope = SubshellScope String | NoneScope deriving (Show, Eq)+data Scope = SubshellScope String | FunctionScope | NoneScope deriving (Show, Eq) data StackData =     StackScope Scope     | StackScopeEnd@@ -149,12 +155,16 @@  -- For testing. If parsed, returns whether there are any comments producesComments :: Checker -> String -> Maybe Bool-producesComments c s = do+producesComments c s = fmap (not . null) $ runAndGetCodes c s++-- If parsed, returns the list of codes+runAndGetCodes :: Checker -> String -> Maybe [Integer]+runAndGetCodes c s = do         let pr = pScript s         prRoot pr         let spec = defaultSpec pr         let params = makeParameters spec-        return . not . null $ filterByAnnotation spec params $ runChecker params c+        return . (sort . map (cCode . tcComment)) $ filterByAnnotation spec params $ runChecker params c  makeComment :: Severity -> Id -> Code -> String -> TokenComment makeComment severity id code note =@@ -197,89 +207,99 @@         }     in force withFix +extendedAnalysisAnnotationToMode :: ExtendedAnalysisAnnotation -> ExtendedAnalysisMode+extendedAnalysisAnnotationToMode m =+    case m of+        EAANone -> ExtendedAnalysisNone+        EAALocal -> ExtendedAnalysisLocal+        EAAFull -> ExtendedAnalysisFull+ -- makeParameters :: CheckSpec -> Parameters makeParameters spec = params   where-    extendedAnalysis = fromMaybe True $ msum [asExtendedAnalysis spec, getExtendedAnalysisDirective root]+    extendedAnalysisMode = fromMaybe ExtendedAnalysisFull $+        msum [asExtendedAnalysis spec, extendedAnalysisAnnotationToMode <$> getExtendedAnalysisDirective root]     params = Parameters {         rootNode = root,         shellType = fromMaybe (determineShell (asFallbackShell spec) root) $ asShellType spec,-        hasSetE = containsSetE root,+        hasAllexport = containsAllexport root,+        hasErrexit = containsErrexit root,+        hasNoglob = containsNoglob root,         hasLastpipe =             case shellType params of-                Bash -> isOptionSet "lastpipe" root+                Bash -> containsLastpipe root                 Dash -> False                 BusyboxSh -> False                 Sh   -> False                 Ksh  -> True,         hasInheritErrexit =             case shellType params of-                Bash -> isOptionSet "inherit_errexit" root+                -- POSIX mode enables inherit_errexit by default in Bash.+                Bash -> containsInheritErrexit root || containsPosix root                 Dash -> True                 BusyboxSh -> True                 Sh   -> True                 Ksh  -> False,-        hasPipefail =+        hasPipefail = containsPipefail root,+        hasExecfail =             case shellType params of-                Bash -> isOptionSet "pipefail" root-                Dash -> True-                BusyboxSh -> isOptionSet "pipefail" root-                Sh   -> True-                Ksh  -> isOptionSet "pipefail" root,+                Bash -> containsExecfail root+                _ -> False,         shellTypeSpecified = isJust (asShellType spec) || isJust (asFallbackShell spec),         idMap = getTokenMap root,         parentMap = getParentTree root,         variableFlow = getVariableFlow params root,         tokenPositions = asTokenPositions spec,         cfgAnalysis = do-            guard extendedAnalysis+            guard $ extendedAnalysisMode /= ExtendedAnalysisNone             return $ CF.analyzeControlFlow cfParams root     }     cfParams = CF.CFGParameters {         CF.cfLastpipe = hasLastpipe params,-        CF.cfPipefail = hasPipefail params+        CF.cfPipefail = hasPipefail params,+        -- In 'local' mode, sourced files are data-flow boundaries: their+        -- bodies are not inlined into the CFG (bounds memory on large+        -- mutually-sourcing trees). See CFG.cfSourceAsBoundary.+        CF.cfSourceAsBoundary = extendedAnalysisMode == ExtendedAnalysisLocal     }     root = asScript spec ---- Does this script mention 'set -e' anywhere?--- Used as a hack to disable certain warnings.-containsSetE root = isNothing $ doAnalysis (guard . not . isSetE) root+-- Detect shell option (`set -o errexit`, `shopt -o -s errexit`, `set -e`, `#!/bin/sh -e`)+-- This is a hack that does not account for flow control, but helps disable certain warnings+isOptionSet :: [Char] -> Maybe Char -> Token -> Bool+isOptionSet longOpt shortOpt root = isNothing $ doAnalysis (guard . not . isSetOption) root   where-    isSetE t =+    shebangRegex c = mkRegex $ "[[:space:]]-[^-]*" ++ [c]+    isSetOption t =         case t of-            T_Script _ (T_Literal _ str) _ -> str `matches` re-            T_SimpleCommand {}  ->-                t `isUnqualifiedCommand` "set" &&-                    ("errexit" `elem` oversimplify t ||-                        "e" `elem` map snd (getAllFlags t))-            _ -> False-    re = mkRegex "[[:space:]]-[^-]*e"-+            T_Script _ (T_Literal _ str) _ | isJust shortOpt ->+                str `matches` shebangRegex (fromJust shortOpt) -containsSetOption opt root = isNothing $ doAnalysis (guard . not . isPipefail) root-  where-    isPipefail t =-        case t of-            T_SimpleCommand {}  ->-                t `isUnqualifiedCommand` "set" &&-                    (opt `elem` oversimplify t ||-                        "o" `elem` map snd (getAllFlags t))+            T_SimpleCommand {}  -> fromMaybe False $ do+                cmd <- getCommandName t+                let flags = map snd $ getAllFlags t+                let strings = oversimplify t+                return $ case cmd of+                    "set" ->+                        (longOpt `elem` strings && "o" `elem` flags) ||+                            isJust shortOpt && [fromJust shortOpt] `elem` flags+                    "shopt" ->+                        longOpt `elem` strings && "s" `elem` flags+                    _ -> False             _ -> False -containsShopt shopt root =-        isNothing $ doAnalysis (guard . not . isShoptLastPipe) root-    where-        isShoptLastPipe t =-            case t of-                T_SimpleCommand {}  ->-                    t `isUnqualifiedCommand` "shopt" &&-                        (shopt `elem` oversimplify t)-                _ -> False+containsErrexit = isOptionSet "errexit" (Just 'e')+containsAllexport = isOptionSet "allexport" (Just 'a')+containsNoglob = isOptionSet "noglob" (Just 'f')+containsPipefail = isOptionSet "pipefail" Nothing+containsLastpipe = isOptionSet "lastpipe" Nothing+containsExecfail = isOptionSet "execfail" Nothing+containsInheritErrexit = isOptionSet "inherit_errexit" Nothing+containsPosix = isOptionSet "posix" Nothing --- Does this script mention 'shopt -s $opt' or 'set -o $opt' anywhere?-isOptionSet opt root = containsShopt opt root || containsSetOption opt root +-- Make sure all shells in supportedShellDialects resolve with shellForExecutable+prop_supportedShellsResolve = isJust $ sequence $ map shellForExecutable supportedShellDialects  prop_determineShell0 = determineShellTest "#!/bin/sh" == Sh prop_determineShell1 = determineShellTest "#!/usr/bin/env ksh" == Ksh@@ -298,14 +318,12 @@ determineShellTest = determineShellTest' Nothing determineShellTest' fallbackShell = determineShell fallbackShell . fromJust . prRoot . pScript determineShell fallbackShell t = fromMaybe Bash $-    shellForExecutable shellString `mplus` fallbackShell+    getCandidate t `mplus` fallbackShell   where-    shellString = getCandidate t-    getCandidate :: Token -> String-    getCandidate t@T_Script {} = fromShebang t-    getCandidate (T_Annotation _ annotations s) =-        headOrDefault (fromShebang s) [s | ShellOverride s <- annotations]-    fromShebang (T_Script _ (T_Literal _ s) _) = executableFromShebang s+    getCandidate (T_Annotation _ annotations s) = fromScript annotations s+    getCandidate s = fromScript [] s+    fromScript annotations (T_Script _ (T_Literal _ s) _) =+        shellFromAnnotations annotations (executableFromShebang s)  -- Given a root node, make a map from Id to parent Token. -- This is used to populate parentMap in Parameters@@ -498,9 +516,11 @@         T_DollarExpansion _ _  -> SubshellScope "$(..) expansion"         T_Backticked _ _  -> SubshellScope "`..` expansion"         T_Backgrounded _ _  -> SubshellScope "backgrounding &"+        T_KshCoprocess _ _  -> SubshellScope "backgrounding |&"         T_Subshell _ _  -> SubshellScope "(..) group"         T_BatsTest {} -> SubshellScope "@bats test"         T_CoProcBody _ _  -> SubshellScope "coproc"+        T_Function {} -> FunctionScope         T_Redirecting {}  ->             if causesSubshell == Just True             then SubshellScope "pipeline"@@ -535,7 +555,9 @@         T_BatsTest {} -> [             (t, t, "lines", DataArray SourceExternal),             (t, t, "status", DataString SourceInteger),-            (t, t, "output", DataString SourceExternal)+            (t, t, "output", DataString SourceExternal),+            (t, t, "stderr", DataString SourceExternal),+            (t, t, "stderr_lines", DataArray SourceExternal)             ]          -- Count [[ -v foo ]] as an "assignment".@@ -557,9 +579,13 @@         T_FdRedirect _ ('{':var) op -> -- {foo}>&2 modifies foo             [(t, t, takeWhile (/= '}') var, DataString SourceInteger) | not $ isClosingFileOp op] -        T_CoProc _ name _ ->-            [(t, t, fromMaybe "COPROC" name, DataArray SourceInteger)]+        T_CoProc _ Nothing _ ->+            [(t, t, "COPROC", DataArray SourceInteger)] +        T_CoProc _ (Just token) _ -> do+            name <- maybeToList $ getLiteralString token+            [(t, t, name, DataArray SourceInteger)]+         --Points to 'for' rather than variable         T_ForIn id str [] _ -> [(t, t, str, DataString SourceExternal)]         T_ForIn id str words _ -> [(t, t, str, DataString $ SourceFrom words)]@@ -575,6 +601,20 @@             _ -> Nothing  +-- Variables set by bats' run command+getBatsRunVariables args =+    [+        ("status", DataString SourceInteger),+        ("output", DataString SourceExternal),+        ("lines", DataArray SourceExternal)+    ] ++ if "--separate-stderr" `elem` opts then [+        ("stderr", DataString SourceExternal),+        ("stderr_lines", DataArray SourceExternal)+    ] else []+  where+    opts = takeWhile (\s -> s == "!" || (s /= "--" && "-" `isPrefixOf` s)) $+        map (fromMaybe "" . getLiteralString) args+ -- Consider 'export/declare -x' a reference, since it makes the var available getReferencedVariableCommand base@(T_SimpleCommand _ _ (T_NormalWord _ (T_Literal _ x:_):rest)) =     case x of@@ -657,12 +697,15 @@          "mapfile" -> maybeToList $ getMapfileArray base rest         "readarray" -> maybeToList $ getMapfileArray base rest+        "compgen" -> maybeToList $ getCompgenArray rest          "DEFINE_boolean" -> maybeToList $ getFlagVariable rest         "DEFINE_float" -> maybeToList $ getFlagVariable rest         "DEFINE_integer" -> maybeToList $ getFlagVariable rest         "DEFINE_string" -> maybeToList $ getFlagVariable rest +        "run" -> [(base, base, name, value) | (name, value) <- getBatsRunVariables rest]+         _ -> []   where     flags = map snd $ getAllFlags base@@ -716,6 +759,14 @@     getPrintfVariable list = getFlagAssignedVariable "v" (SourceFrom list) $ getBsdOpts "v:" list     getWaitVariable   list = getFlagAssignedVariable "p" SourceInteger     $ return $ getGenericOpts list +    -- compgen -V arr stores the completions in the array arr rather than printing them+    getCompgenArray list = do+        let flags = getGenericOpts list+        (_, (_, value)) <- find ((== "V") . fst) flags+        name <- getLiteralString value+        guard $ isVariableName name+        return (base, value, name, DataArray SourceExternal)+     getFlagAssignedVariable str dataSource maybeFlags = do         flags <- maybeFlags         (_, (flag, value)) <- find ((== str) . fst) flags@@ -790,12 +841,6 @@             then concatMap (getIfReference t) [lhs, rhs]             else [] -        T_BatsTest {} -> [ -- pretend @test references vars to avoid warnings-            (t, t, "lines"),-            (t, t, "status"),-            (t, t, "output")-            ]-         T_FdRedirect _ ('{':var) op -> -- {foo}>&- references and closes foo             [(t, t, takeWhile (/= '}') var) | isClosingFileOp op]         x -> getReferencedVariableCommand x@@ -902,16 +947,6 @@ supportsArrays Ksh = True supportsArrays _ = False --- Returns true if the shell is Bash or Ksh (sorry for the name, Ksh)-isBashLike :: Parameters -> Bool-isBashLike params =-    case shellType params of-        Bash -> True-        Ksh -> True-        Dash -> False-        BusyboxSh -> False-        Sh -> False- isTrueAssignmentSource c =     case c of         DataString SourceChecked -> False@@ -928,6 +963,30 @@         case t of             Assignment (_, _, n, source) -> isTrueAssignmentSource source && n == name             _ -> False++isTestCommand t =+    case t of+        T_Condition {} -> True+        T_SimpleCommand {} -> t `isCommand` "test"+        T_Redirecting _ _ t -> isTestCommand t+        T_Annotation _ _ t -> isTestCommand t+        T_Pipeline _ _ [t] -> isTestCommand t+        _ -> False++-- Checks whether the current parent path is part of a condition+isCondition (x NE.:| xs) = foldr go (const False) xs x+  where+    go _ _ T_BatsTest{} = True -- count anything in a @test as conditional+    go parent go_rest child =+        getId child `elem` map getId (getConditionChildren parent) || go_rest parent+    getConditionChildren t =+        case t of+            T_AndIf _ left right -> [left]+            T_OrIf id left right -> [left]+            T_IfExpression id conditions elses -> concatMap (take 1 . reverse . fst) conditions+            T_WhileExpression id c l -> take 1 . reverse $ c+            T_UntilExpression id c l -> take 1 . reverse $ c+            _ -> []   return []
src/ShellCheck/CFG.hs view
@@ -160,7 +160,7 @@   deriving (Eq, Ord, Show, Generic, NFData)  -- The properties of a variable-data CFVariableProp = CFVPExport | CFVPArray | CFVPAssociative | CFVPInteger+data CFVariableProp = CFVPExport | CFVPArray | CFVPAssociative | CFVPInteger | CFVPReadonly   deriving (Eq, Ord, Show, Generic, NFData)  -- Options when generating CFG@@ -168,7 +168,11 @@     -- Whether the last element in a pipeline runs in the current shell     cfLastpipe :: Bool,     -- Whether all elements in a pipeline count towards the exit status-    cfPipefail :: Bool+    cfPipefail :: Bool,+    -- Treat 'source'd files as data-flow boundaries: don't inline their+    -- bodies into the CFG. Bounds memory when many inputs source a shared+    -- tree (each includer would otherwise re-analyze the whole tree).+    cfSourceAsBoundary :: Bool }  data CFGResult = CFGResult {@@ -270,10 +274,10 @@             [(Id 0, 3)]             )         after = (-            [(1,s), (2,s), (4,s)],-            [(1,2,CFEFlow), (2,4,CFEFlow)],-            [(Id 0, (2,2))],-            [(Id 0, 2)]+            [(1,s), (3,s), (4,s)],+            [(1,3,CFEFlow), (3,4,CFEFlow)],+            [(Id 0, (3,3))],+            [(Id 0, 3)]             )     in after == removeUnnecessaryStructuralNodes before @@ -293,21 +297,20 @@         )   where     regularEdges = filter isRegularEdge edges-    inDegree = counter $ map (\(from,to,_) -> from) regularEdges-    outDegree = counter $ map (\(from,to,_) -> to) regularEdges-    structuralNodes = S.fromList $ map fst $ filter isStructural nodes+    inDegree = counter $ map (\(from,to,_) -> to) regularEdges+    outDegree = counter $ map (\(from,to,_) -> from) regularEdges+    structuralNodes = S.fromList [node | (node, CFStructuralNode) <- nodes]     candidateNodes = S.filter isLinear structuralNodes     edgesToCollapse = S.fromList $ filter filterEdges regularEdges      remapping :: M.Map Node Node-    remapping = foldl' (\m (new, old) -> M.insert old new m) M.empty $ map orderEdge $ S.toList edgesToCollapse-    recursiveRemapping = M.fromList $ map (\c -> (c, recursiveLookup remapping c)) $ M.keys remapping+    remapping = M.fromList $ map (\(a,b,_) -> (a,b)) $ S.toList edgesToCollapse+    recursiveRemapping = M.mapWithKey (\c _ -> recursiveLookup remapping c) remapping      filterEdges (a,b,_) =         a `S.member` candidateNodes && b `S.member` candidateNodes -    orderEdge (a,b,_) = if a < b then (a,b) else (b,a)-    counter = foldl' (\map key -> M.insertWith (+) key 1 map) M.empty+    counter = M.fromListWith (+) . map (\key -> (key, 1))     isRegularEdge (_, _, CFEFlow) = True     isRegularEdge _ = False @@ -317,11 +320,6 @@             Nothing -> node             Just x -> recursiveLookup map x -    isStructural (node, label) =-        case label of-            CFStructuralNode -> True-            _ -> False-     isLinear node =         M.findWithDefault 0 node inDegree == 1         && M.findWithDefault 0 node outDegree == 1@@ -495,7 +493,7 @@         TA_Binary _ _ a b -> sequentially [a,b]         TA_Expansion _ list -> sequentially list         TA_Sequence _ list -> sequentially list-        TA_Parentesis _ t -> build t+        TA_Parenthesis _ t -> build t          TA_Trinary _ cond a b -> do             condition <- build cond@@ -581,16 +579,9 @@          T_Assignment {} -> buildAssignment Nothing t -        T_Backgrounded id body -> do-            start <- newStructuralNode-            fork <- subshell id "backgrounding '&'" $ build body-            pid <- newNodeRange $ CFSetBackgroundPid id-            status <- newNodeRange $ CFSetExitCode id+        T_Backgrounded id body -> buildBackground id "backgrounding '&'" body -            linkRange start fork-            -- Add a join from the fork to warn about variable changes-            linkRangeAs CFEFalseFlow fork pid-            linkRanges [start, pid, status]+        T_KshCoprocess id body -> buildBackground id "backgrounding '|&'" body          T_Backticked id body ->             subshell id "`..` expansion" $ sequentially body@@ -617,66 +608,70 @@          T_CaseExpression id t list@(hd:tl) -> do             start <- newStructuralNode-            token <- build t-            branches <- mapM buildBranch (hd NE.:| tl)             end <- newStructuralNode+            token <- build t+            branches <- mapM (buildBranch end) (hd NE.:| tl) -            let neighbors = zip (NE.toList branches) $ NE.tail branches-            let (_, firstCond, _) = NE.head branches-            let (_, lastCond, lastBody) = NE.last branches+            let neighbors = zip (NE.toList branches) $ (NE.tail branches ++ [(end, end, undefined, undefined)])+            let (firstCond, _, _, _) = NE.head branches              linkRange start token             linkRange token firstCond-            mapM_ (uncurry $ linkBranch end) neighbors-            linkRange lastBody end--            unless (any hasCatchAll list) $-                -- There's no *) branch, so assume we can fall through-                void $ linkRange token end+            mapM_ (uncurry linkBranch) neighbors              return $ spanRange start end            where+            buildBranch end (typ, cond, body) = do+                bodyNode <- sequentially body+                condNode <- buildCond bodyNode cond+                nextCondNode <- newStructuralNode+                nextBodyNode <- newStructuralNode+                case typ of+                    CaseBreak -> linkRange bodyNode end+                    CaseFallThrough -> linkRange bodyNode nextBodyNode+                    CaseContinue -> linkRange bodyNode nextCondNode+                linkRange condNode nextCondNode+                return (condNode, bodyNode, nextCondNode, nextBodyNode)+             -- for a | b | c, evaluate each in turn and allow short circuiting-            buildCond list = do-                start <- newStructuralNode-                conds <- mapM build list-                end <- newStructuralNode-                linkRanges (start:conds)-                mapM_ (`linkRange` end) conds-                return $ spanRange start end+            buildCond _ [] = newStructuralNode+            buildCond body (alt:rest) = do+                altNode <- build alt+                linkRange altNode body -            buildBranch (typ, cond, body) = do-                c <- buildCond cond-                b <- sequentially body-                linkRange c b-                return (typ, c, b)+                let isCatchAll = fromMaybe False $ do+                        pg <- wordToExactPseudoGlob alt+                        return $ pg `pseudoGlobIsSuperSetof` [PGMany] -            linkBranch end (typ, cond, body) (_, nextCond, nextBody) = do-                -- Failure case-                linkRange cond nextCond-                -- After body-                case typ of-                    CaseBreak -> linkRange body end-                    CaseFallThrough -> linkRange body nextBody-                    CaseContinue -> linkRange body nextCond+                nextNode <- buildCond body rest+                unless isCatchAll $+                    void $ linkRange altNode nextNode -            -- Find a *) if any+                return $ spanRange altNode nextNode -            hasCatchAll (_,cond,_) = any isCatchAll cond-            isCatchAll c = fromMaybe False $ do-                pg <- wordToExactPseudoGlob c-                return $ pg `pseudoGlobIsSuperSetof` [PGMany]+            linkBranch (cond, body, nextCond, nextBody) (cond2, body2, nextCond2, nextBody2) = do+                linkRange nextCond cond2+                linkRange nextBody body2 -        T_Condition id _ op -> do++        T_Condition id _ _ op -> do             cond <- build op             status <- newNodeRange $ CFSetExitCode id             linkRange cond status -        T_CoProc id maybeName t -> do-            let name = fromMaybe "COPROC" maybeName+        T_CoProc id maybeNameToken t -> do+            -- If unspecified, "COPROC". If not a constant string, Nothing.+            let maybeName = case maybeNameToken of+                    Just x -> getLiteralString x+                    Nothing -> Just "COPROC"++            let parentNode = case maybeName of+                    Just str -> applySingle $ IdTagged id $ CFWriteVariable str CFValueArray+                    Nothing -> CFStructuralNode+             start <- newStructuralNode-            parent <- newNodeRange $ applySingle $ IdTagged id $ CFWriteVariable name CFValueArray+            parent <- newNodeRange parentNode             child <- subshell id "coproc" $ build t             end <- newNodeRange $ CFSetExitCode id @@ -713,6 +708,9 @@                 linkRange totalRead result               else return totalRead +        T_DollarBraceCommandExpansion id _ body ->+            sequentially body+         T_DoubleQuoted _ list -> sequentially list          T_DollarExpansion id body ->@@ -865,11 +863,19 @@          T_SourceCommand _ originalCommand inlinedSource -> do             cmd <- build originalCommand-            end <- newStructuralNode-            inline <- withReturn end $ build inlinedSource-            linkRange cmd inline-            linkRange inline end-            return $ spanRange cmd inline+            sourceAsBoundary <- reader $ cfSourceAsBoundary . cfParameters+            if sourceAsBoundary+              then+                -- Data-flow boundary: do not inline the sourced body into the CFG.+                -- Functions/vars it defines become opaque here; the file is+                -- analyzed on its own when it is itself an input.+                return cmd+              else do+                end <- newStructuralNode+                inline <- withReturn end $ build inlinedSource+                linkRange cmd inline+                linkRange inline end+                return $ spanRange cmd inline          T_Subshell id body -> do             main <- subshell id "explicit (..) subshell" $ sequentially body@@ -893,6 +899,17 @@             none  --  Still in `where` clause+    buildBackground id reason body = do+        start <- newStructuralNode+        fork <- subshell id reason $ build body+        pid <- newNodeRange $ CFSetBackgroundPid id+        status <- newNodeRange $ CFSetExitCode id++        linkRange start fork+        -- Add a join from the fork to warn about variable changes+        linkRangeAs CFEFalseFlow fork pid+        linkRanges [start, pid, status]+     forInHelper id name words body = do         entry <- newStructuralNode         expansion <- sequentially words@@ -922,7 +939,7 @@         linkRange condRange end  -handleCommand cmd vars args literalCmd = do+handleCommand simpleCmdToken vars args literalCmd = do     -- TODO: Handle assignments in declaring commands      case literalCmd of@@ -933,6 +950,7 @@         Just "declare" -> handleDeclare args         Just "local" -> handleDeclare args         Just "typeset" -> handleDeclare args+        Just "readonly" -> handleDeclare args          Just "printf" -> regularExpansionWithStatus vars args $ handlePrintf args         Just "wait" -> regularExpansionWithStatus vars args $ handleWait args@@ -952,16 +970,16 @@             case args of                 _ NE.:| [] -> regular                 (_ NE.:| newcmd:newargs) ->-                    handleCommand newcmd vars (newcmd NE.:| newargs) $ getLiteralString newcmd+                    handleCommand simpleCmdToken vars (newcmd NE.:| newargs) $ getLiteralString newcmd         Just "command" ->             case args of                 _ NE.:| [] -> regular                 (_ NE.:| newcmd:newargs) ->-                    handleOthers (getId newcmd) vars (newcmd NE.:| newargs) $ getLiteralString newcmd+                    handleOthers (getId simpleCmdToken) vars (newcmd NE.:| newargs) $ getLiteralString newcmd         _ -> regular    where-    regular = handleOthers (getId cmd) vars args literalCmd+    regular = handleOthers (getId simpleCmdToken) vars args literalCmd     handleExit = do         exitNode <- reader cfExitTarget         case exitNode of@@ -985,7 +1003,7 @@                 unreachable <- newNode CFUnreachable                 return $ Range ret unreachable -    handleUnset (cmd NE.:| args) = do+    handleUnset (_ NE.:| args) = do         case () of                 _ | "n" `elem` flagNames -> unsetWith CFUndefineNameref                 _ | "v" `elem` flagNames -> unsetWith CFUndefineVariable@@ -1004,7 +1022,7 @@      variableAssignRegex = mkRegex "^([_a-zA-Z][_a-zA-Z0-9]*)=" -    handleDeclare (cmd NE.:| args) = do+    handleDeclare (_ NE.:| args) = do         isFunc <- asks cfIsFunction         -- This is a bit of a kludge: we don't have great support for things like         -- 'declare -i x=$x' so do one round with declare x=$x, followed by declare -i x@@ -1013,7 +1031,7 @@         assignments <- newNodeRange $ CFApplyEffects assignments         addedProps <- if null added then newStructuralNode else newNodeRange $ CFApplyEffects added         removedProps <- if null removed then newStructuralNode else newNodeRange $ CFApplyEffects removed-        result <- newNodeRange $ CFSetExitCode (getId cmd)+        result <- newNodeRange $ CFSetExitCode (getId simpleCmdToken)         linkRanges [before, assignments, addedProps, removedProps, result]       where         opts = map fst $ getGenericOpts args@@ -1023,23 +1041,28 @@         func = "f" `elem` opts || "F" `elem` opts         global = "g" `elem` opts         export = "x" `elem` opts+        -- 'readonly' is like 'declare -r', except it doesn't make variables local+        isReadonlyCommand = literalCmd == Just "readonly"+        readonly = "r" `elem` opts || isReadonlyCommand         writer isFunc =             case () of                 _ | global -> CFWriteGlobal-                _ | isFunc -> CFWriteLocal+                _ | isFunc && not isReadonlyCommand -> CFWriteLocal                 _ -> CFWriteVariable          scope isFunc =             case () of                 _ | global -> Just GlobalScope-                _ | isFunc -> Just LocalScope+                _ | isFunc && not isReadonlyCommand -> Just LocalScope                 _ -> Nothing          addedProps = S.fromList $ concat $ [             [ CFVPArray | array ],             [ CFVPInteger | integer ],             [ CFVPExport | export ],-            [ CFVPAssociative | associative ]+            [ CFVPAssociative | associative ],+            -- 'readonly -f' and 'declare -rf' apply to functions, not variables+            [ CFVPReadonly | readonly && not func ]           ]          removedProps = S.fromList $ concat $ [@@ -1093,7 +1116,7 @@             in                 concatMap (drop 1) plusses -    handlePrintf (cmd NE.:| args) =+    handlePrintf (_ NE.:| args) =         newNodeRange $ CFApplyEffects $ maybeToList findVar       where         findVar = do@@ -1102,7 +1125,7 @@             name <- getLiteralString arg             return $ IdTagged (getId arg) $ CFWriteVariable name CFValueString -    handleWait (cmd NE.:| args) =+    handleWait (_ NE.:| args) =         newNodeRange $ CFApplyEffects $ maybeToList findVar       where         findVar = do@@ -1111,11 +1134,11 @@             name <- getLiteralString arg             return $ IdTagged (getId arg) $ CFWriteVariable name CFValueInteger -    handleMapfile (cmd NE.:| args) =+    handleMapfile (_ NE.:| args) =         newNodeRange $ CFApplyEffects [findVar]       where         findVar =-            let (id, name) = fromMaybe (getId cmd, "MAPFILE") $ getFromArg `mplus` getFromFallback+            let (id, name) = fromMaybe (getId simpleCmdToken, "MAPFILE") $ getFromArg `mplus` getFromFallback             in IdTagged id $ CFWriteVariable name CFValueArray          getFromArg = do@@ -1131,7 +1154,7 @@             guard $ isVariableName name             return (getId c, name) -    handleRead (cmd NE.:| args) = newNodeRange $ CFApplyEffects main+    handleRead (_ NE.:| args) = newNodeRange $ CFApplyEffects main       where         main = fromMaybe fallback $ do             flags <- getGnuOpts flagsForRead args@@ -1155,13 +1178,13 @@         fallback =             let                 names = reverse $ map fromJust $ takeWhile isJust $ map (\c -> sequence (getId c, getLiteralString c)) $ reverse args-                namesOrDefault = if null names then [(getId cmd, "REPLY")] else names+                namesOrDefault = if null names then [(getId simpleCmdToken, "REPLY")] else names                 hasDashA = any (== "a") $ map fst $ getGenericOpts args                 value = if hasDashA then CFValueArray else CFValueString             in                 map (\(id, name) -> IdTagged id $ CFWriteVariable name value) namesOrDefault -    handleDEFINE (cmd NE.:| args) =+    handleDEFINE (_ NE.:| args) =         newNodeRange $ CFApplyEffects $ maybeToList findVar       where         findVar = do@@ -1170,9 +1193,9 @@             guard $ isVariableName str             return $ IdTagged (getId name) $ CFWriteVariable str CFValueString -    handleOthers id vars args cmd =+    handleOthers id vars args maybeName =         regularExpansion vars (NE.toList args) $ do-            exe <- newNodeRange $ CFExecuteCommand cmd+            exe <- newNodeRange $ CFExecuteCommand maybeName             status <- newNodeRange $ CFSetExitCode id             linkRange exe status @@ -1190,9 +1213,9 @@              linkRanges $ [args] ++ assignments ++ [exe] ++ dropAssignments -    regularExpansionWithStatus vars args@(cmd NE.:| _) p = do+    regularExpansionWithStatus vars args p = do         initial <- regularExpansion vars (NE.toList args) p-        status <- newNodeRange $ CFSetExitCode (getId cmd)+        status <- newNodeRange $ CFSetExitCode (getId simpleCmdToken)         linkRange initial status  
src/ShellCheck/CFGAnalysis.hs view
@@ -20,7 +20,6 @@ {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DeriveAnyClass, DeriveGeneric #-}-{-# LANGUAGE CPP #-}  {-     Data Flow Analysis on a Control Flow Graph.@@ -61,6 +60,7 @@     ,doesPostDominate     ,variableMayBeDeclaredInteger     ,variableMayBeAssignedInteger+    ,variableMustBeDeclaredReadonly     ,ShellCheck.CFGAnalysis.runTests -- STRIP     ) where @@ -133,7 +133,7 @@             literalValue = Nothing         }     }-    flatVars = M.unionsWith (\_ last -> last) $ map mapStorage [sGlobalValues s, sLocalValues s, sPrefixValues s]+    flatVars = M.unions $ map mapStorage [sPrefixValues s, sLocalValues s, sGlobalValues s]  -- Conveniently get the state before a token id getIncomingState :: CFGAnalysis -> Id -> Maybe ProgramState@@ -161,9 +161,18 @@     value <- M.lookup var $ variablesInScope state     return $ any (S.member property) $ variableProperties value +-- See if every execution path results in the variable containing a state+variableMustHaveState :: ProgramState -> String -> CFVariableProp -> Maybe Bool+variableMustHaveState state var property = do+    value <- M.lookup var $ variablesInScope state+    return $ all (S.member property) $ variableProperties value+ -- See if any execution path declares the variable an integer (declare -i). variableMayBeDeclaredInteger state var = variableMayHaveState state var CFVPInteger +-- See if every execution path declares the variable readonly (readonly, declare -r).+variableMustBeDeclaredReadonly state var = variableMustHaveState state var CFVPReadonly+ -- See if any execution path suggests the variable may contain an integer value variableMayBeAssignedInteger state var = do     value <- M.lookup var $ variablesInScope state@@ -449,14 +458,6 @@ }     deriving (Eq, Generic, NFData) -#if MIN_VERSION_deepseq(1,4,2)--- Our deepseq already has a STRef instance-#else--- Older deepseq (for GHC < 8) lacks this instance-instance NFData (STRef s a) where-    rnf = (`seq` ())-#endif- -- Overwrite a base state with the contents of a diff state -- This is unrelated to join/merge. patchState :: InternalState -> InternalState -> InternalState@@ -672,7 +673,7 @@         _ | vmIsQuickEqual base diff -> diff         _ -> VersionedMap {             mapVersion = -1,-            mapStorage = M.unionWith (flip const) (mapStorage base) (mapStorage diff)+            mapStorage = M.union (mapStorage diff) (mapStorage base)         }  -- Set a variable. This includes properties. Applies it to the appropriate scope.@@ -1286,7 +1287,7 @@             else do                 let (next, rest) = S.deleteFindMin ps                 nexts <- process states next-                writeSTRef pending $ foldl (flip S.insert) rest nexts+                writeSTRef pending $ S.union (S.fromList nexts) rest                 f (n-1) pending states      process states node = do@@ -1350,7 +1351,7 @@          -- All nodes we've touched         invocations <- readSTRef $ cInvocations ctx-        let invokedNodes = M.fromDistinctAscList $ map (\c -> (c, ())) $ S.toList $ M.keysSet $ groupByNode $ M.map snd invocations+        let invokedNodes = M.fromSet (const ()) $ S.unions $ map (M.keysSet . snd) $ M.elems invocations          -- Invoke all functions that were declared but not invoked         -- This is so that we still get warnings for dead code@@ -1373,7 +1374,7 @@          -- Fill in the map with unreachable states for anything we didn't get to         let baseStates = M.fromDistinctAscList $ map (\c -> (c, (unreachableState, unreachableState))) $ uncurry enumFromTo $ nodeRange $ cfGraph cfg-        let allStates = M.unionWith (flip const) baseStates invokedStates+        let allStates = M.union invokedStates baseStates          -- Convert to external states         let nodeToData = M.map (\(a,b) -> (internalToExternal a, internalToExternal b)) allStates
src/ShellCheck/Checker.hs view
@@ -22,6 +22,8 @@  import ShellCheck.Analyzer import ShellCheck.ASTLib+import ShellCheck.Data (shellFromFilename)+import ShellCheck.EditorConfig import ShellCheck.Interface import ShellCheck.Parser @@ -50,17 +52,6 @@   where     fail = error "Internal shellcheck error: id doesn't exist. Please report!" -shellFromFilename filename = listToMaybe candidates-  where-    shellExtensions = [(".ksh", Ksh)-                      ,(".bash", Bash)-                      ,(".bats", Bash)-                      ,(".dash", Dash)]-                      -- The `.sh` is too generic to determine the shell:-                      -- We fallback to Bash in this case and emit SC2148 if there is no shebang-    candidates =-        [sh | (ext,sh) <- shellExtensions, ext `isSuffixOf` filename]- checkScript :: Monad m => SystemInterface m -> CheckSpec -> m CheckResult checkScript sys spec = do     results <- checkScript (csScript spec)@@ -164,8 +155,92 @@         siFindSource = mapper     } +-- shellcheck.* directives extracted from an EditorConfig file are merged+-- into the same "key=value" blob as .shellcheckrc. We simulate that here+-- by feeding editorConfigDirectives' output through siGetConfig.+checkWithEditorConfig ec name src =+    let sys = (mockedSystemInterface [("foo", src)]) {+            siGetConfig = const . return $+                Just (".editorconfig", fromMaybe "" $ editorConfigDirectives ec name)+        }+    in getErrors sys emptyCheckSpec {+        csScript = src,+        csExcludedWarnings = [2148]+    }++prop_editorConfigAppliesKnownShell =+    null $ checkWithEditorConfig "[foo]\nshellcheck.shell=bash\n" "foo"+        "#!/bin/sh\necho \"hi\""+prop_editorConfigAppliesDisable =+    null $ checkWithEditorConfig "[foo]\nshellcheck.disable=SC2086\n" "foo"+        "#!/bin/sh\necho $1"+prop_editorConfigUnknownShellIsReported =+    -- An unknown shell can't be applied silently; it surfaces as a+    -- config parse error (SC1134) rather than being dropped.+    [1134] == checkWithEditorConfig "[foo]\nshellcheck.shell=zsh\n" "foo"+        "#!/bin/sh\necho \"hi\""+prop_editorConfigCommentValueIsReported =+    -- EditorConfig has no inline comments, so a '#'-prefixed value is+    -- reported as a config error (SC1134) instead of being eaten.+    [1134] == checkWithEditorConfig "[foo]\nshellcheck.disable=#abc\n" "foo"+        "#!/bin/sh\necho \"hi\""+prop_editorConfigNonMatchingSectionIgnored =+    -- A directive in a section whose glob does not match the file is+    -- not applied (and produces no config error).+    [2086] == checkWithEditorConfig "[bar]\nshellcheck.disable=SC2086\n" "foo"+        "#!/bin/sh\necho $1"+ prop_findsParseIssue = check "echo \"$12\"" == [1037] +prop_kshCoprocessRead =+    null $ check "#!/bin/ksh\nprintf '%s\\n' data |&\nread -pr record\nprintf '%s\\n' \"$record\""++prop_kshCoprocessReadWithoutSpaces =+    null $ check "#!/bin/ksh\nprintf '%s\\n' data|&read -r record <&p\nprintf '%s\\n' \"$record\""++prop_kshCoprocessAssignmentScope =+    [2030, 2031] == check "#!/bin/ksh\nvalue=parent\nvalue=child && : |&\nwait \"$!\"\nprintf '%s\\n' \"$value\""++prop_kshCoprocessEof = null $ check "#!/bin/ksh\ntrue|&"++prop_kshCoprocessFilename =+    null $ checkWithSpec [] emptyCheckSpec {+        csFilename = "example.ksh",+        csScript = "true|&"+    }++prop_kshCoprocessDirective =+    null $ check "#!/bin/bash\n#shellcheck shell=ksh\ntrue|&"++prop_kshCoprocessRc =+    null $ checkWithRc "shell=ksh\n" emptyCheckSpec {+        csScript = "#!/bin/bash\ntrue|&"+    }++prop_kshCoprocessDirectiveOverridesRc =+    null $ checkWithRc "shell=bash\n" emptyCheckSpec {+        csScript = "#!/bin/bash\n#shellcheck shell=ksh\ntrue|&"+    }++prop_kshCoprocessOverride =+    null $ checkWithSpec [] emptyCheckSpec {+        csShellTypeOverride = Just Ksh,+        csScript = "#!/bin/bash\ntrue|&"+    }++prop_kshCoprocessInSourcedCode =+    null $ checkWithIncludes [("helper", "#!/bin/bash\ntrue |&")] "#!/bin/ksh\n. helper"++prop_bashStderrPipe = null $ check "#!/bin/bash\nprintf '%s\\n' data |&\ncat"++prop_bashOverrideKeepsStderrPipe =+    [1072] == checkWithSpec [] emptyCheckSpec {+        csShellTypeOverride = Just Bash,+        csScript = "#!/bin/ksh\n#shellcheck shell=ksh\ntrue|&"+    }++prop_shStderrPipe = check "#!/bin/sh\nprintf '%s\\n' data |& cat" == [3029]+ prop_commentDisablesParseIssue1 =     null $ check "#shellcheck disable=SC1037\necho \"$12\"" prop_commentDisablesParseIssue2 =@@ -221,6 +296,9 @@ prop_worksWhenSourcingWithDashDash =     null $ checkWithIncludes [("lib", "bar=1")] "source -- lib; echo \"$bar\"" +prop_worksWhenSourcingWithDashP =+    null $ checkWithIncludes [("lib", "bar=1")] "source -p \"$MYPATH\" lib; echo \"$bar\""+ prop_worksWhenDotting =     null $ checkWithIncludes [("lib", "bar=1")] ". lib; echo \"$bar\"" @@ -305,6 +383,13 @@         csScript = "(( 3.14 ))"     } +prop_deducesTypeFromEnvrcExtension = result == [2079]+  where+    result = checkWithSpec [] emptyCheckSpec {+        csFilename = ".envrc",+        csScript = "(( 3.14 ))"+    }+ prop_canDisableShebangWarning = null $ result   where     result = checkWithSpec [] emptyCheckSpec {@@ -312,6 +397,56 @@         csScript = "#shellcheck disable=SC2148\nfoo"     } +prop_warnsButIgnoresLeadingCommentWithFilename = [1113, 2148] == result+  where+    result = checkWithSpec [] emptyCheckSpec {+        csFilename = "file.sh",+        csScript = "# /usr/bin/python is an interpreter\n/usr/bin/python \"$@\""+    }++prop_canIgnoreLeadingFormatWarning1 = [2148] == result+  where+    result = checkWithSpec [] emptyCheckSpec {+        csFilename = "file.sh",+        csScript = "# /usr/bin/python is an interpreter\n# shellcheck disable=SC1113\n/usr/bin/python \"$@\""+    }++-- This technically avoids the warning, but either way+prop_canIgnoreLeadingFormatWarning2 = [2148] == result+  where+    result = checkWithSpec [] emptyCheckSpec {+        csFilename = "file.sh",+        csScript = "# shellcheck disable=SC1113\n# /usr/bin/python is an interpreter\n/usr/bin/python \"$@\""+    }++prop_canIgnoreLeadingFormatWarning3 = null result+  where+    result = checkWithSpec [] emptyCheckSpec {+        csFilename = "file.sh",+        csScript = "# /etc/profile -- Shell Initialization\n# shellcheck disable=SC1113 shell=sh\nVAR=VALUE\nexport VAR\n"+    }++prop_onlyFirstLineCanTriggerMissingBangWarning = [2148] == result+  where+    result = checkWithSpec [] emptyCheckSpec {+        csFilename = "file.sh",+        csScript = "# shell init file\n# /etc/profile is my name and init is my game\n echo 'Hello World' >&2\n"+    }++prop_bangInLeadingCommentIsNotShebang = [2086] == result+  where+    result = checkWithSpec [] emptyCheckSpec {+        csFilename = "file.bash",+        csScript = "# Notes:\n#  ! python is needed for the helper\necho $1\n"+    }++prop_stillWarnsAboutSpacedShebangAfterComment = [1115, 1128] == result+  where+    result = checkWithSpec [] emptyCheckSpec {+        csFilename = "file.sh",+        csScript = "# Copyright\n#  !/bin/sh\necho b\n"+    }+ prop_canDisableAllWarnings = result == [2086]   where     result = checkWithSpec [] emptyCheckSpec {@@ -341,6 +476,14 @@         csCheckSourced = True     } +prop_sourcedCommandInExpansionDoesntCrash = result == [2034]+  where+    result = checkWithSpec [("lib.sh", "echo hello")] emptyCheckSpec {+        csFilename = "file.bash",+        csScript = "x=$(source lib.sh)",+        csCheckSourced = True+    }+ prop_canEnableOptionalsWithSpec = result == [2244]   where     result = checkWithSpec [] emptyCheckSpec {@@ -394,6 +537,13 @@         csIgnoreRC = False     } +prop_unknownRcDirectiveGetsWarning = result == [1107, 2086]+  where+    result = checkWithRc "foo=bar" emptyCheckSpec {+        csScript = "#!/bin/sh\necho $1",+        csIgnoreRC = False+    }+ prop_canEnableOptionalsWithRc = result == [2244]   where     result = checkWithRc "enable=avoid-nullary-conditions" emptyCheckSpec {@@ -549,15 +699,48 @@ prop_flagWinsWhenSuppressingDfa1 = result == [2317]   where     result = checkWithRc "extended-analysis=false" emptyCheckSpec {-        csScript = "#!/bin/sh\n# shellcheck extended-analysis=false\nexit; foo;",-        csExtendedAnalysis = Just True+        csScript = "#!/bin/sh\n# shellcheck extended-analysis=none\nexit; foo;",+        csExtendedAnalysis = Just ExtendedAnalysisFull     }  prop_flagWinsWhenSuppressingDfa2 = null result   where     result = checkWithRc "extended-analysis=true" emptyCheckSpec {-        csScript = "#!/bin/sh\n# shellcheck extended-analysis=true\nexit; foo;",-        csExtendedAnalysis = Just False+        csScript = "#!/bin/sh\n# shellcheck extended-analysis=full\nexit; foo;",+        csExtendedAnalysis = Just ExtendedAnalysisNone+    }++-- 'local' still does data-flow analysis within a file...+prop_localKeepsIntraFileDfa = 2317 `elem` result+  where+    result = getErrors (mockedSystemInterface []) emptyCheckSpec {+        csScript = "#!/bin/sh\nexit; foo;",+        csExtendedAnalysis = Just ExtendedAnalysisLocal+    }++-- ...but treats sourced files as boundaries, so it does not use data flow+-- from a sourced file (here: that f() always exits) the way 'full' does.+prop_localTreatsSourcesAsBoundary = 2317 `notElem` result+  where+    result = getErrors (mockedSystemInterface [("lib", "f() { exit 1; }")]) emptyCheckSpec {+        csScript = "#!/bin/sh\nsource lib\nf\nfoo",+        csCheckSourced = True,+        csExtendedAnalysis = Just ExtendedAnalysisLocal+    }++prop_localDirectiveTreatsSourcesAsBoundary = 2317 `notElem` result+  where+    result = getErrors (mockedSystemInterface [("lib", "f() { exit 1; }")]) emptyCheckSpec {+        csScript = "#!/bin/sh\n# shellcheck extended-analysis=local\nsource lib\nf\nfoo",+        csCheckSourced = True+    }++prop_fullFollowsDataFlowIntoSources = 2317 `elem` result+  where+    result = getErrors (mockedSystemInterface [("lib", "f() { exit 1; }")]) emptyCheckSpec {+        csScript = "#!/bin/sh\nsource lib\nf\nfoo",+        csCheckSourced = True,+        csExtendedAnalysis = Just ExtendedAnalysisFull     }  return []
src/ShellCheck/Checks/Commands.hs view
@@ -62,6 +62,9 @@ verify f s = producesComments (getChecker [f]) s == Just True verifyNot f s = producesComments (getChecker [f]) s == Just False +verifyCodes :: CommandCheck -> String -> [Integer] -> Bool+verifyCodes f s c = runAndGetCodes (getChecker [f]) s == Just c+ commandChecks :: [CommandCheck] commandChecks = [     checkTr@@ -99,18 +102,21 @@     ,checkMvArguments, checkCpArguments, checkLnArguments     ,checkFindRedirections     ,checkReadExpansions-    ,checkSudoRedirect-    ,checkSudoArgs     ,checkSourceArgs     ,checkChmodDashr     ,checkXargsDashi     ,checkUnquotedEchoSpaces     ,checkEvalArray+    ,checkGrepSendsPipefail+    ,checkEgrepSendsPipefail+    ,checkFgrepSendsPipefail     ]     ++ map checkArgComparison ("alias" : declaringCommands)     ++ map checkMaskedReturns declaringCommands     ++ map checkMultipleDeclaring declaringCommands     ++ map checkBackreferencingDeclaration declaringCommands+    ++ map checkSudoArgs privilegeElevationCommands+    ++ map checkSudoRedirect privilegeElevationCommands   optionalChecks = map fst optionalCommandChecks@@ -118,6 +124,7 @@ optionalCommandChecks = [     (newCheckDescription {         cdName = "deprecate-which",+        cdId = [2230],         cdDescription = "Suggest 'command -v' instead of 'which'",         cdPositive = "which javac",         cdNegative = "command -v javac"@@ -128,7 +135,7 @@ prop_verifyOptionalExamples = all check optionalCommandChecks   where     check (desc, check) =-      verify check (cdPositive desc)+      runAndGetCodes (getChecker [check]) (cdPositive desc) == Just (cdId desc)       && verifyNot check (cdNegative desc)  -- Run a check against the getopt parser. If it fails, the lists are empty.@@ -400,10 +407,88 @@     contra = mkRegex "[^a-zA-Z1-9]\\*|[][^$+\\\\]"  +prop_checkGrepSendsPipefail1 = verify checkGrepSendsPipefail "set -o pipefail; cat file | grep -q pattern"+prop_checkGrepSendsPipefail2 = verify checkGrepSendsPipefail "set -o pipefail; cat file | grep --quiet pattern"+prop_checkGrepSendsPipefail3 = verify checkGrepSendsPipefail "set -o pipefail; cat file | grep -iq pattern"+prop_checkGrepSendsPipefail4 = verify checkGrepSendsPipefail "set -o pipefail; cmd1 | cmd2 | grep -q pattern"+prop_checkGrepSendsPipefail5 = verify checkGrepSendsPipefail "set -euo pipefail; cmd | grep -q foo"+prop_checkGrepSendsPipefail6 = verify checkGrepSendsPipefail "set -o pipefail; if cmd | grep -m 2 foo | cmd2; then true; fi"+prop_checkGrepSendsPipefail7 = verify checkGrepSendsPipefail "set -e -o pipefail; cmd | grep -L foo | cmd2"++prop_checkGrepSendsPipefailN1 = verifyNot checkGrepSendsPipefail "cat file | grep -q pattern"+prop_checkGrepSendsPipefailN2 = verifyNot checkGrepSendsPipefail "set -o pipefail; grep -q pattern file"+prop_checkGrepSendsPipefailN3 = verifyNot checkGrepSendsPipefail "set -o pipefail; cat file | grep pattern"+prop_checkGrepSendsPipefailN4 = verifyNot checkGrepSendsPipefail "set -o pipefail; grep -q pattern | cat"+prop_checkGrepSendsPipefailN5 = verifyNot checkGrepSendsPipefail "grep -q pattern file"+prop_checkGrepSendsPipefailN6 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | bash -c 'grep -q pattern file'"+prop_checkGrepSendsPipefailN7 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | grep -e -q"+prop_checkGrepSendsPipefailN8 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | grep -eq pattern"+prop_checkGrepSendsPipefailN9 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | grep --regexp -q"+prop_checkGrepSendsPipefailN10 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd1 | grep -- -q"+prop_checkGrepSendsPipefailN11 = verifyNot checkGrepSendsPipefail "set -o pipefail; cmd | grep -m 2 foo | cmd2"++checkGrepSendsPipefail = CommandCheck (Basename "grep") checkGrepSendsPipefailImpl++prop_checkEgrepSendsPipefail1 = verify checkEgrepSendsPipefail "set -o pipefail; cat file | egrep -q pattern"+checkEgrepSendsPipefail = CommandCheck (Basename "egrep") checkGrepSendsPipefailImpl++prop_checkFgrepSendsPipefail1 = verify checkFgrepSendsPipefail "set -o pipefail; cat file | fgrep -q pattern"+checkFgrepSendsPipefail = CommandCheck (Basename "fgrep") checkGrepSendsPipefailImpl++-- Catches occurrences of "grep -q" and variants, such as "-m" or "-L", inside of pipes under pipefail.+checkGrepSendsPipefailImpl cmd = do+    pipefail <- asks hasPipefail+    errexit <- asks hasErrexit+    astPath <- getPathM cmd+    sequence_ $ do+        guard pipefail+        opts <- map fst <$> parseGrepOpts (arguments cmd)+        let isQuiet = any (`elem` quietFlags) opts+        let isEarlyExit = isQuiet || any (`elem` earlyExitFlags) opts+        guard $ isEarlyExit+        _simpleCmd:grepRedirectingCmd:parentNodes <- Just $ NE.toList astPath+        T_Pipeline _ _ (_first:redirectingCmds) <- listToMaybe parentNodes+        guard $ any (\node -> getId node == getId grepRedirectingCmd) redirectingCmds+        guard $ isQuiet || errexit || isCondition (grepRedirectingCmd NE.:| parentNodes)+        return $ warn (getId cmd) 2337 warnMsg+  where+    -- Contains "L", even though BSD grep does not exit early with this flag,+    -- but GNU grep does. This is consistent with the linter practice of warning+    -- about potential problems, while also allowing users to disable specific+    -- linter checks locally.+    quietFlags = ["q", "quiet", "--silent"]+    earlyExitFlags = ["m", "max-count", "L"]+    parseGrepOpts = getOpts (True, True)+        "cilLnoqsvwxhHrRbaEFGPe:f:m:A:B:C:d:D:"+        (map (\name -> (name, True)) longOptionsConsumingParameter)+    longOptionsConsumingParameter =+        ["regexp", "file", "max-count", "after-context", "before-context",+            "context", "directories", "devices"]+    warnMsg = "In pipefail mode, the exit code of grep -q/-m/-L is subject to a race. " +++              "Use a non-pipe input like '< <(cmd)' or '<<<' instead."++ prop_checkTrapQuotes1 = verify checkTrapQuotes "trap \"echo $num\" INT" prop_checkTrapQuotes1a = verify checkTrapQuotes "trap \"echo `ls`\" INT" prop_checkTrapQuotes2 = verifyNot checkTrapQuotes "trap 'echo $num' INT" prop_checkTrapQuotes3 = verify checkTrapQuotes "trap \"echo $((1+num))\" EXIT DEBUG"+prop_checkTrapQuotes4 = verifyNot checkTrapQuotes "readonly num; trap \"echo $num\" INT"+prop_checkTrapQuotes5 = verifyNot checkTrapQuotes "num=1; readonly num; trap \"echo ${num}\" INT"+prop_checkTrapQuotes6 = verifyNot checkTrapQuotes "declare -r num=1; trap \"echo $num\" INT"+prop_checkTrapQuotes7 = verifyNot checkTrapQuotes "typeset -r num=1; trap \"echo $num\" INT"+prop_checkTrapQuotes8 = verify checkTrapQuotes "trap \"echo $num\" INT; readonly num"+prop_checkTrapQuotes9 = verify checkTrapQuotes "declare num=1; trap \"echo $num\" INT"+prop_checkTrapQuotes10 = verifyNot checkTrapQuotes "f() { readonly num=1; }; f; trap \"echo $num\" ERR"+prop_checkTrapQuotes11 = verify checkTrapQuotes "readonly num; f() { local num; trap \"echo $num\" ERR; }"+prop_checkTrapQuotes12 = verifyNot checkTrapQuotes "f() { local -r num; trap \"echo $num\" ERR; }"+prop_checkTrapQuotes13 = verify checkTrapQuotes "readonly num; trap \"echo $num $other\" ERR"+prop_checkTrapQuotes14 = verify checkTrapQuotes "[ \"$1\" ] && readonly num; trap \"echo $num\" ERR"+prop_checkTrapQuotes15 = verifyNot checkTrapQuotes "if [ \"$1\" ]; then readonly num=1; else readonly num=2; fi; trap \"echo $num\" ERR"+prop_checkTrapQuotes16 = verify checkTrapQuotes "f() { readonly num=1; }; trap \"echo $num\" ERR"+prop_checkTrapQuotes17 = verify checkTrapQuotes "readonly -f num; trap \"echo $num\" ERR"+prop_checkTrapQuotes18 = verifyNot checkTrapQuotes "builtin readonly num; trap \"echo $num\" ERR"+prop_checkTrapQuotes19 = verify checkTrapQuotes "f() { local -r num; }; f; trap \"echo $num\" ERR"+prop_checkTrapQuotes20 = verifyNot checkTrapQuotes "f() { declare -gr num; }; f; trap \"echo $num\" ERR" checkTrapQuotes = CommandCheck (Exactly "trap") (f . arguments) where     f (x:_) = checkTrap x     f _ = return ()@@ -412,11 +497,22 @@     warning id = warn id 2064 "Use single quotes, otherwise this expands now rather than when signalled."     checkExpansions (T_DollarExpansion id _) = warning id     checkExpansions (T_Backticked id _) = warning id-    checkExpansions (T_DollarBraced id _ _) = warning id+    checkExpansions (T_DollarBraced id _ word) = do+        params <- ask+        let name = concat $ oversimplify word+        unless (isVariableName name && isReadonly params id name) $+            warning id     checkExpansions (T_DollarArithmetic id _) = warning id     checkExpansions _ = return () +    -- A readonly variable can never change value, so it doesn't matter+    -- whether it's expanded now or when the trap runs.+    isReadonly params id name = fromMaybe False $ do+        cfga <- cfgAnalysis params+        state <- CF.getIncomingState cfga id+        CF.variableMustBeDeclaredReadonly state name + prop_checkReturn1 = verifyNot checkReturn "return" prop_checkReturn2 = verifyNot checkReturn "return 1" prop_checkReturn3 = verifyNot checkReturn "return $var"@@ -424,9 +520,31 @@ prop_checkReturn5 = verify checkReturn "return -1" prop_checkReturn6 = verify checkReturn "return 1000" prop_checkReturn7 = verify checkReturn "return 'hello world'"-checkReturn = CommandCheck (Exactly "return") (returnOrExit-        (\c -> err c 2151 "Only one integer 0-255 can be returned. Use stdout for other data.")-        (\c -> err c 2152 "Can only return 0-255. Other data should be written to stdout."))+-- Return a safe value.+prop_checkReturn8A = verifyCodes checkReturn "#!/bin/sh\nf() { return 0; }; f" []+prop_checkReturn8B = verifyCodes checkReturn "#!/bin/bash\nf() { return 0; }; f" []+prop_checkReturn8C = verifyCodes checkReturn "#!/bin/dash\nf() { return 0; }; f" []+prop_checkReturn8D = verifyCodes checkReturn "#!/bin/ksh\nf() { return 0; }; f" []+prop_checkReturn8E = verifyCodes checkReturn "#!/bin/busybox sh\nf() { return 0; }; f" []+-- Return not-a-number. Not supported on any shell, but bash treats it as 2, ksh as 0, the rest error.+prop_checkReturn9A = verifyCodes checkReturn "#!/bin/sh\nf() { return asdf; }; f" [2152]+prop_checkReturn9B = verifyCodes checkReturn "#!/bin/bash\nf() { return asdf; }; f" [2152]+prop_checkReturn9C = verifyCodes checkReturn "#!/bin/dash\nf() { return asdf; }; f" [2152]+prop_checkReturn9D = verifyCodes checkReturn "#!/bin/ksh\nf() { return asdf; }; f" [2152]+prop_checkReturn9E = verifyCodes checkReturn "#!/bin/busybox sh\nf() { return asdf; }; f" [2152]+-- Return negative. Dash and Busybox error, bash wraps, ksh allows.+prop_checkReturn10A = verifyCodes checkReturn "#!/bin/sh\nf() { return -1; }; f" [3426]+prop_checkReturn10B = verifyCodes checkReturn "#!/bin/bash\nf() { return -1; }; f" [2341]+prop_checkReturn10C = verifyCodes checkReturn "#!/bin/dash\nf() { return -1; }; f" [2339]+prop_checkReturn10D = verifyCodes checkReturn "#!/bin/ksh\nf() { return -1; }; f" []+prop_checkReturn10E = verifyCodes checkReturn "#!/bin/busybox sh\nf() { return -1; }; f" [2339]+-- Return out-of-bounds. Bash and Busybox error, bash wraps, dash and ksh allows.+prop_checkReturn11A = verifyCodes checkReturn "#!/bin/sh\nf() { return 1000; }; f" [3426]+prop_checkReturn11B = verifyCodes checkReturn "#!/bin/bash\nf() { return 1000; }; f" [2341]+prop_checkReturn11C = verifyCodes checkReturn "#!/bin/dash\nf() { return 1000; }; f" []+prop_checkReturn11D = verifyCodes checkReturn "#!/bin/ksh\nf() { return 1000; }; f" []+prop_checkReturn11E = verifyCodes checkReturn "#!/bin/busybox sh\nf() { return 1000; }; f" [2341]+checkReturn = CommandCheck (Exactly "return") (returnOrExit False)  prop_checkExit1 = verifyNot checkExit "exit" prop_checkExit2 = verifyNot checkExit "exit 1"@@ -435,22 +553,77 @@ prop_checkExit5 = verify checkExit "exit -1" prop_checkExit6 = verify checkExit "exit 1000" prop_checkExit7 = verify checkExit "exit 'hello world'"-checkExit = CommandCheck (Exactly "exit") (returnOrExit-        (\c -> err c 2241 "The exit status can only be one integer 0-255. Use stdout for other data.")-        (\c -> err c 2242 "Can only exit with status 0-255. Other data should be written to stdout/stderr."))+-- Exit with a safe value.+prop_checkExit8A = verifyCodes checkExit "#!/bin/sh\nexit 0" []+prop_checkExit8B = verifyCodes checkExit "#!/bin/bash\nexit 0" []+prop_checkExit8C = verifyCodes checkExit "#!/bin/dash\nexit 0" []+prop_checkExit8D = verifyCodes checkExit "#!/bin/ksh\nexit 0" []+prop_checkExit8E = verifyCodes checkExit "#!/bin/busybox sh\nexit 0" []+-- Exit not-a-number. Not supported on any shell, but ksh treats it as 0.+prop_checkExit9A = verifyCodes checkExit "#!/bin/sh\nexit asdf" [2242]+prop_checkExit9B = verifyCodes checkExit "#!/bin/bash\nexit asdf" [2242]+prop_checkExit9C = verifyCodes checkExit "#!/bin/dash\nexit asdf" [2242]+prop_checkExit9D = verifyCodes checkExit "#!/bin/ksh\nexit adsf" [2242]+prop_checkExit9E = verifyCodes checkExit "#!/bin/busybox sh\nexit asdf" [2242]+-- Exit negative. Dash and Busybox error. Bash and Ksh wrap.+prop_checkExit10A = verifyCodes checkExit "#!/bin/sh\nexit -1" [3426]+prop_checkExit10B = verifyCodes checkExit "#!/bin/bash\nexit -1" [2340]+prop_checkExit10C = verifyCodes checkExit "#!/bin/dash\nexit -1" [2339]+prop_checkExit10D = verifyCodes checkExit "#!/bin/ksh\nexit -1" [2340]+prop_checkExit10E = verifyCodes checkExit "#!/bin/busybox sh\nexit -1" [2339]+-- Return out-of-bounds. They all wrap.+prop_checkExit11A = verifyCodes checkExit "#!/bin/sh\nexit 1000" [3426]+prop_checkExit11B = verifyCodes checkExit "#!/bin/bash\nexit 1000" [2340]+prop_checkExit11C = verifyCodes checkExit "#!/bin/dash\nexit 1000" [2340]+prop_checkExit11D = verifyCodes checkExit "#!/bin/ksh\nexit 1000" [2340]+prop_checkExit11E = verifyCodes checkExit "#!/bin/busybox sh\nexit 1000" [2340]+checkExit = CommandCheck (Exactly "exit") (returnOrExit True) -returnOrExit multi invalid = (f . arguments)-  where-    f (first:second:_) =-        multi (getId first)-    f [value] =-        when (isInvalid $ literal value) $-            invalid (getId value)-    f _ = return ()+returnOrExit :: Bool -> Token -> Analysis+returnOrExit isExit cmd =+    case arguments cmd of+        (first:second:_) ->+            if isExit+            then err (getId first) 2241 "The exit status can only be one integer 0-255. Use stdout for other data."+            else err (getId first) 2151 "Only one integer 0-255 can be returned. Use stdout for other data."+        [] -> return ()+        [arg] -> do+            shell <- asks shellType+            let id = getId arg+            let returnRange =+                    case shell of+                        Sh -> "0-255"+                        Bash -> "0-255"+                        BusyboxSh -> "0-255"+                        Ksh -> "an integer"+                        Dash -> "an integer" -- a positive one, at that -    isInvalid s = null s || any (not . isDigit) s || length s > 5-        || let value = (read s :: Integer) in value > 255+            let (isNegative, isOutOfRange, isNaN) = properties arg+            -- These cases have strong overlap, so order matters.+            case shell of+                _ | isNaN ->+                    if isExit+                    then err id 2242 "Can only exit with status 0-255. Other data should be written to stdout/stderr."+                    else err id 2152 $ "Can only return " ++ returnRange ++ ". Other data should be written to stdout." +                Sh        | isNegative || isOutOfRange -> err id 3426 "Return/exit values outside 0-255 are undefined in POSIX sh."+                Dash      | isNegative -> err id 2339 "Dash does not wrap negative return/exit values. Use a positive integer."+                BusyboxSh | isNegative -> err id 2339 "Busybox does not wrap negative return/exit values. Use a positive integer."++                _ | isExit && isOutOfRange -> warn id 2340 "Exit codes wrap to the range of 0-255. Prefer a canonical exit code."++                Bash | isOutOfRange -> warn id 2341 "Bash wraps return codes to the range 0-255. Prefer a canonical return code."+                BusyboxSh | isOutOfRange -> warn id 2341 "Busybox wraps return codes to the range 0-255. Prefer a canonical return code."++                _ -> return ()+  where+    properties :: Token -> (Bool, Bool, Bool) -- Return whether token (isNegative, isOutOfRange (0-256), isNaN)+    properties t =+        case literal t of+            '-':s | all isDigit s -> (True, True, False)+            s | all isDigit s -> (False, (read s :: Integer) >= 256, False)+            _ -> (False, False, True)+     literal token = runIdentity $ getLiteralStringExt lit token     lit (T_DollarBraced {}) = return "0"     lit (T_DollarArithmetic {}) = return "0"@@ -470,9 +643,9 @@         termS <- getLiteralString term         let cmdS = getLiteralStringDef " " arg -        guard $ execS `elem` ["-exec", "-execdir"] && termS `elem` [";", "+"]+        guard $ execS `elem` ["-exec", "-execdir", "-ok", "-okdir"] && termS `elem` [";", "+"]         guard $ cmdS `matches` commandRegex-        return $ warn (getId exec) 2150 "-exec does not invoke a shell. Rewrite or use -exec sh -c .. ."+        return $ warn (getId exec) 2150 (execS ++ " does not invoke a shell. Rewrite or use " ++ execS ++ " sh -c .. .")     check _ = Nothing     commandRegex = mkRegex "[ |;]" @@ -505,7 +678,7 @@  prop_checkInjectableFindSh1 = verify checkInjectableFindSh "find . -exec sh -c 'echo {}' \\;" prop_checkInjectableFindSh2 = verify checkInjectableFindSh "find . -execdir bash -c 'rm \"{}\"' ';'"-prop_checkInjectableFindSh3 = verifyNot checkInjectableFindSh "find . -exec sh -c 'rm \"$@\"' _ {} \\;"+prop_checkInjectableFindSh3 = verifyNot checkInjectableFindSh "find . -ok sh -c 'rm \"$@\"' _ {} \\;" checkInjectableFindSh = CommandCheck (Basename "find") (check . arguments)   where     check args = do@@ -519,7 +692,7 @@         match (p:tests) args      pattern = [-        (`elem` ["-exec", "-execdir"]),+        (`elem` ["-exec", "-execdir", "-ok", "-okdir"]),         (`elem` ["sh", "bash", "dash", "ksh"]),         (== "-c")         ]@@ -678,10 +851,12 @@ prop_checkPrintfVar20 = verifyNot checkPrintfVar "printf '%d %(%s)T' 42" prop_checkPrintfVar21 = verify checkPrintfVar "printf '%d %(%s)T'" prop_checkPrintfVar22 = verify checkPrintfVar "printf '%s\n%s' foo"+prop_checkPrintfVar23 = verifyNot checkPrintfVar "printf -vTODAY '%(%Y)T'"  checkPrintfVar = CommandCheck (Exactly "printf") (f . arguments) where     f (doubledash:rest) | getLiteralString doubledash == Just "--" = f rest     f (dashv:var:rest) | getLiteralString dashv == Just "-v" = f rest+    f (dashvVar:rest) | Just ('-':'v':_:_) <- getLiteralString dashvVar = f rest     f (format:params) = check format params     f _ = return () @@ -691,7 +866,7 @@             let formats = getPrintfFormats string             let formatCount = length formats             let argCount = length more-            let pluraliseIfMany word n = if n > 1 then word ++ "s" else word+            let pluraliseIfMany word n = if n == 1 then word else word ++ "s"              return $ if                 | argCount == 0 && formatCount == 0 ->@@ -725,6 +900,9 @@ prop_checkGetPrintfFormats5 = getPrintfFormats "%bPassed: %d, %bFailed: %d%b, Skipped: %d, %bErrored: %d%b\\n" == "bdbdbdbdb" prop_checkGetPrintfFormats6 = getPrintfFormats "%s%s" == "ss" prop_checkGetPrintfFormats7 = getPrintfFormats "%s\n%s" == "ss"+prop_checkGetPrintfFormats8 = getPrintfFormats "%ld" == "d"+prop_checkGetPrintfFormats9 = getPrintfFormats "%lld" == "d"+prop_checkGetPrintfFormats10 = getPrintfFormats "%Q" == "Q" getPrintfFormats = getFormats   where     -- Get the arguments in the string as a string of type characters,@@ -743,17 +921,17 @@      regexBasedGetFormats rest =         case matchRegex re rest of-            Just [width, precision, typ, rest, _] ->+            Just [width, precision, len, typ, rest, _] ->                 (if width == "*" then "*" else "") ++                 (if precision == "*" then "*" else "") ++                 typ ++ getFormats rest             Nothing -> take 1 rest ++ getFormats rest       where         -- constructed based on specifications in "man printf"-        re = mkRegex "#?-?\\+? ?0?(\\*|\\d*)\\.?(\\d*|\\*)([diouxXfFeEgGaAcsbq])((\n|.)*)"-        --            \____ _____/\___ ____/   \____ ____/\_________ _________/ \______ /-        --                 V          V             V               V               V-        --               flags    field width  precision   format character        rest+        re = mkRegex "^#?-?\\+? ?0?(\\*|\\d*)\\.?(\\d*|\\*)(hh|h|l|ll|q|L|j|z|Z|t)?([diouxXfFeEgGaAcsbqQSC])((\n|.)*)"+        --             \____ _____/\___ ____/   \____ ____/\__________ ___________/\___________ ___________/\___ ___/+        --                  V          V             V                V                        V                V+        --                flags    field width  precision        length modifier      format character         rest         -- field width and precision can be specified with an '*' instead of a digit,         -- in which case printf will accept one more argument for each '*' used @@ -894,6 +1072,13 @@ prop_checkFindWithoutPath6 = verifyNot checkFindWithoutPath "find -D exec ." prop_checkFindWithoutPath7 = verifyNot checkFindWithoutPath "find --help" prop_checkFindWithoutPath8 = verifyNot checkFindWithoutPath "find -Hx . -print"+prop_checkFindWithoutPath9 = verifyNot checkFindWithoutPath "find -files0-from - < file"+prop_checkFindWithoutPath10 = verifyNot checkFindWithoutPath "find -files0-from 'paths list.nul' -print"+prop_checkFindWithoutPath11 = verifyNot checkFindWithoutPath "find -L '-files0-from' \"$paths\" -print"+prop_checkFindWithoutPath12 = verify checkFindWithoutPath "find -L"+prop_checkFindWithoutPath13 = verify checkFindWithoutPath "find -L -files0-from"+prop_checkFindWithoutPath14 = verify checkFindWithoutPath "find -name '-files0-from' -print"+prop_checkFindWithoutPath15 = verify checkFindWithoutPath "find -exec echo -files0-from {} \\;" checkFindWithoutPath = CommandCheck (Basename "find") f   where     f t@(T_SimpleCommand _ _ (cmd:args)) =@@ -904,9 +1089,11 @@     -- after the path, as well as multiple non-flag arguments that are not the     -- path. We assume that all the pre-path flags are single characters from a     -- list of GNU and macOS flags.-    hasPath (first:rest) =-        let flag = getLiteralStringDef "___" first in-            not ("-" `isPrefixOf` flag) || isLeadingFlag flag && hasPath rest+    hasPath (first:rest)+        | flag == "-files0-from" = not (null rest)+        | otherwise = not ("-" `isPrefixOf` flag) || isLeadingFlag flag && hasPath rest+      where+        flag = getLiteralStringDef "___" first     hasPath [] = False     isLeadingFlag flag = length flag <= 2 || all (`elem` leadingFlagChars) flag     leadingFlagChars="-EHLPXdfsxO0123456789"@@ -1083,32 +1270,76 @@ prop_checkCatastrophicRm11 = verify checkCatastrophicRm "rm -r /{bin,sbin}/$exec" prop_checkCatastrophicRm12 = verify checkCatastrophicRm "rm -r /{{usr,},{bin,sbin}}/$exec" prop_checkCatastrophicRm13 = verifyNot checkCatastrophicRm "rm -r /{{a,b},{c,d}}/$exec"-prop_checkCatastrophicRmA = verify checkCatastrophicRm "rm -rf /usr /lib/nvidia-current/xorg/xorg"-prop_checkCatastrophicRmB = verify checkCatastrophicRm "rm -rf \"$STEAMROOT/\"*"-checkCatastrophicRm = CommandCheck (Basename "rm") $ \t ->-    when (isRecursive t) $-        mapM_ (mapM_ checkWord . braceExpand) $ arguments t+prop_checkCatastrophicRm13A= verify checkCatastrophicRm "rm -rf /usr /lib/nvidia-current/xorg/xorg"+prop_checkCatastrophicRm13B= verify checkCatastrophicRm "rm -rf \"$STEAMROOT/\"*"+prop_checkCatastrophicRm13C= verify checkCatastrophicRm "rm -rf /boot/*"+prop_checkCatastrophicRm14 = verify checkCatastrophicRm "rm -rf /./etc"+prop_checkCatastrophicRm15 = verify checkCatastrophicRm "rm -rf /etc/../etc"+prop_checkCatastrophicRm16 = verifyNot checkCatastrophicRm "rm -rf /usr/local/../etc"+prop_checkCatastrophicRm17 = verify checkCatastrophicRm "rm -rf /etc/.."+prop_checkCatastrophicRm18 = verify checkCatastrophicRm "rm -rf /./etc/*"+prop_checkCatastrophicRm19 = verifyNot checkCatastrophicRm "rm -rf /etc/*/../foo"+prop_checkCatastrophicRm20 = verify checkCatastrophicRm "rm -rf \"$x/../etc\""+prop_checkCatastrophicRm21 = verifyNot checkCatastrophicRm "rm -rf ../etc"+prop_checkCatastrophicRm22 = verifyNot checkCatastrophicRm "rm -rf foo/../etc"+prop_checkCatastrophicRm23 = verify checkCatastrophicRm "rm -rf /etc/./"+prop_checkCatastrophicRm24 = verify checkCatastrophicRm "rm -rf /*/../etc/"+prop_checkCatastrophicRm25 = verifyNot checkCatastrophicRm "rm -rf /etc/*/../etc"+prop_checkCatastrophicRm26 = verifyNot checkCatastrophicRm "rm -rf /usr/*/../local/etc"+prop_checkCatastrophicRm27 = verify checkCatastrophicRm "rm /bin/*"+prop_checkCatastrophicRm28 = verifyNot checkCatastrophicRm "rm /bin"+prop_checkCatastrophicRm29 = verifyNot checkCatastrophicRm "rm '/bin/*'"+prop_checkCatastrophicRm30 = verifyNot checkCatastrophicRm "rm /home/$foo"+prop_checkCatastrophicRm31 = verify checkCatastrophicRm "rm /home/*$foo*"+checkCatastrophicRm = CommandCheck (Basename "rm") $ \t -> do+    let recursive = isRecursive t+    mapM_ (mapM_ (checkWord recursive) . braceExpand) $ arguments t   where     isRecursive = any ((`elem` ["r", "R", "recursive"]) . snd) . getAllFlags -    checkWord token =-        case getLiteralString token of+    checkWord recursive token =+      when (recursive || isGlob token) $+        case getGlobOrLiteralString token of             Just str ->                 when (fixPath str `elem` importantPaths) $                     warn (getId token) 2114 "Warning: deletes a system directory."-            Nothing ->-                checkWord' token+            Nothing -> checkWord' recursive token -    checkWord' token = sequence_ $ do+    checkWord' recursive token = sequence_ $ do         filename <- getPotentialPath token         let path = fixPath filename-        return . when (path `elem` importantPaths) $+        return . when (path `elem` importantPaths && (recursive || isGlob token)) $             warn (getId token) 2115 $ "Use \"${var:?}\" to ensure this never expands to " ++ path ++ " ."      fixPath filename =         let normalized = skipRepeating '/' . skipRepeating '*' $ filename in-            if normalized == "/" then normalized else stripTrailing '/' normalized+            if normalized == "/" then normalized else+                canonicalize $ stripTrailing '/' normalized +    -- Lexically resolve "." and ".." components so that e.g. "/./etc",+    -- "/etc/../etc" and "/*/../etc" are recognized. A ".." pops the nearest+    -- previous segment, glob or concrete: "/*" expands to top-level entries+    -- "/name", so "/name/../etc" is exactly "/etc". Only a leading ".." of a+    -- relative path survives, since there is nothing above it to pop.+    canonicalize path =+        case resolve [] $ splitPath path of+            [""] | "/" `isPrefixOf` path -> "/"+            resolved -> intercalate "/" resolved+      where+        splitPath s =+            case break (== '/') s of+                (seg, '/':rest) -> seg : splitPath rest+                (seg, _) -> [seg]+        resolve done [] = reverse done+        resolve done (seg:rest)+            | seg == "." = resolve done rest+            | seg == ".." =+                case done of+                    top:d | top /= ".." && top /= "" -> resolve d rest+                    "":_ -> resolve done rest+                    _ -> resolve (seg:done) rest+            | otherwise = resolve (seg:done) rest+     getPotentialPath = getLiteralStringExt f       where         f (T_Glob _ str) = return str@@ -1126,8 +1357,10 @@         go a r = a : case r of b:rest | b == c && a == b -> rest; _ -> r      paths = [-        "", "/bin", "/etc", "/home", "/mnt", "/usr", "/usr/share", "/usr/local",-        "/var", "/lib", "/dev", "/media", "/boot", "/lib64", "/usr/bin"+        "", "/bin", "/boot", "/dev", "/etc", "/home", "/lib", "/lib64", "/media",+        "/mnt", "/opt", "/proc", "/root", "/run", "/sbin", "/srv", "/sys", "/usr",+        "/usr/bin", "/usr/include", "/usr/lib", "/usr/libexec", "/usr/lib64",+        "/usr/local", "/usr/sbin", "/usr/share", "/var"         ]     importantPaths = filter (not . null) $         ["", "/", "/*", "/*/*"] >>= (\x -> map (++x) paths)@@ -1196,14 +1429,14 @@ checkWhich = CommandCheck (Basename "which") $     \t -> info (getId $ getCommandTokenOrThis t) 2230 "'which' is non-standard. Use builtin 'command -v' instead." -prop_checkSudoRedirect1 = verify checkSudoRedirect "sudo echo 3 > /proc/file"-prop_checkSudoRedirect2 = verify checkSudoRedirect "sudo cmd < input"-prop_checkSudoRedirect3 = verify checkSudoRedirect "sudo cmd >> file"-prop_checkSudoRedirect4 = verify checkSudoRedirect "sudo cmd &> file"-prop_checkSudoRedirect5 = verifyNot checkSudoRedirect "sudo cmd 2>&1"-prop_checkSudoRedirect6 = verifyNot checkSudoRedirect "sudo cmd 2> log"-prop_checkSudoRedirect7 = verifyNot checkSudoRedirect "sudo cmd > /dev/null 2>&1"-checkSudoRedirect = CommandCheck (Basename "sudo") f+prop_checkSudoRedirect1 = verify (checkSudoRedirect "sudo") "sudo echo 3 > /proc/file"+prop_checkSudoRedirect2 = verify (checkSudoRedirect "doas") "doas cmd < input"+prop_checkSudoRedirect3 = verify (checkSudoRedirect "run0") "run0 cmd >> file"+prop_checkSudoRedirect4 = verify (checkSudoRedirect "sudo") "sudo cmd &> file"+prop_checkSudoRedirect5 = verifyNot (checkSudoRedirect "sudo") "sudo cmd 2>&1"+prop_checkSudoRedirect6 = verifyNot (checkSudoRedirect "doas") "doas cmd 2> log"+prop_checkSudoRedirect7 = verifyNot (checkSudoRedirect "run0") "run0 cmd > /dev/null 2>&1"+checkSudoRedirect cmd = CommandCheck (Basename cmd) f   where     f t = do         t_redir <- getClosestCommandM t@@ -1215,33 +1448,33 @@         case op of             T_Less _ ->               info (getId op) 2024-                "sudo doesn't affect redirects. Use sudo cat file | .."+                "sudo/doas/run0 doesn't affect redirects. Use sudo cat file | .."             T_Greater _ ->               warn (getId op) 2024-                "sudo doesn't affect redirects. Use ..| sudo tee file"+                "sudo/doas/run0 doesn't affect redirects. Use ..| sudo tee file"             T_DGREAT _ ->               warn (getId op) 2024-                "sudo doesn't affect redirects. Use .. | sudo tee -a file"+                "sudo/doas/run0 doesn't affect redirects. Use .. | sudo tee -a file"             _ -> return ()     warnAbout _ = return ()     special file = concat (oversimplify file) == "/dev/null" -prop_checkSudoArgs1 = verify checkSudoArgs "sudo cd /root"-prop_checkSudoArgs2 = verify checkSudoArgs "sudo export x=3"-prop_checkSudoArgs3 = verifyNot checkSudoArgs "sudo ls /usr/local/protected"-prop_checkSudoArgs4 = verifyNot checkSudoArgs "sudo ls && export x=3"-prop_checkSudoArgs5 = verifyNot checkSudoArgs "sudo echo ls"-prop_checkSudoArgs6 = verifyNot checkSudoArgs "sudo -n -u export ls"-prop_checkSudoArgs7 = verifyNot checkSudoArgs "sudo docker export foo"-checkSudoArgs = CommandCheck (Basename "sudo") f+prop_checkSudoArgs1 = verify (checkSudoArgs "sudo") "sudo cd /root"+prop_checkSudoArgs2 = verify (checkSudoArgs "run0") "run0 export x=3"+prop_checkSudoArgs3 = verifyNot (checkSudoArgs "sudo") "sudo ls /usr/local/protected"+prop_checkSudoArgs4 = verifyNot (checkSudoArgs "doas") "doas ls && export x=3"+prop_checkSudoArgs5 = verifyNot (checkSudoArgs "sudo") "sudo echo ls"+prop_checkSudoArgs6 = verifyNot (checkSudoArgs "sudo") "sudo -n -u export ls"+prop_checkSudoArgs7 = verifyNot (checkSudoArgs "sudo") "sudo docker export foo"+checkSudoArgs cmd = CommandCheck (Basename cmd) f   where     f t = sequence_ $ do         opts <- parseOpts $ arguments t         (_,(commandArg, _)) <- find (null . fst) opts         command <- getLiteralString commandArg         guard $ command `elem` builtins-        return $ warn (getId t) 2232 $ "Can't use sudo with builtins like " ++ command ++ ". Did you want sudo sh -c .. instead?"-    builtins = [ "cd", "eval", "export", "history", "read", "source", "wait" ]+        return $ warn (getId t) 2232 $ "Can't use sudo/doas/run0 with builtins like " ++ command ++ ". Did you want sudo/doas/run0 sh -c .. instead?"+    builtins = [ "cd", "command", "declare", "eval", "exec", "exit", "export", "hash", "history", "local", "popd", "pushd", "read", "readonly", "return", "set", "source", "trap", "type", "typeset", "ulimit", "umask", "unset", "wait" ]     -- This mess is why ShellCheck prefers not to know.     parseOpts = getBsdOpts "vAknSbEHPa:g:h:p:u:c:T:r:" @@ -1431,9 +1664,8 @@ checkBackreferencingDeclaration cmd = CommandCheck (Exactly cmd) check   where     check t = do-        cfga <- asks cfgAnalysis-        when (isJust cfga) $-            foldM_ (perArg $ fromJust cfga) M.empty $ arguments t+        maybeCfga <- asks cfgAnalysis+        mapM_ (\cfga -> foldM_ (perArg cfga) M.empty $ arguments t) maybeCfga      perArg cfga leftArgs t =         case t of
src/ShellCheck/Checks/ControlFlow.hs view
@@ -78,7 +78,7 @@ runNodeChecks :: [ControlFlowNodeCheck] -> ControlFlowCheck runNodeChecks perNode = do     cfg <- asks cfgAnalysis-    sequence_ $ runOnAll <$> cfg+    mapM_ runOnAll cfg   where     getData datas n@(node, label) = do         (pre, post) <- M.lookup node datas
src/ShellCheck/Checks/Custom.hs view
@@ -1,7 +1,7 @@ {-     This empty file is provided for ease of patching in site specific checks.     However, there are no guarantees regarding compatibility between versions.--} +-}  {-# LANGUAGE TemplateHaskell #-} module ShellCheck.Checks.Custom (checker, ShellCheck.Checks.Custom.runTests) where
src/ShellCheck/Checks/ShellSupport.hs view
@@ -63,6 +63,7 @@     ,checkPS1Assignments     ,checkMultipleBangs     ,checkBangAfterPipe+    ,checkNegatedUnaryOps     ]  testChecker (ForShell _ t) =@@ -86,7 +87,7 @@   prop_checkBashisms = verify checkBashisms "while read a; do :; done < <(a)"-prop_checkBashisms2 = verify checkBashisms "[ foo -nt bar ]"+prop_checkBashisms2 = verifyNot checkBashisms "[ foo -nt bar ]" prop_checkBashisms3 = verify checkBashisms "echo $((i++))" prop_checkBashisms4 = verify checkBashisms "rm !(*.hs)" prop_checkBashisms5 = verify checkBashisms "source file"@@ -147,8 +148,8 @@ prop_checkBashisms54 = verify checkBashisms "#!/bin/sh\nfoo+=bar" prop_checkBashisms55 = verify checkBashisms "#!/bin/sh\necho ${@%foo}" prop_checkBashisms56 = verifyNot checkBashisms "#!/bin/sh\necho ${##}"-prop_checkBashisms57 = verifyNot checkBashisms "#!/bin/dash\nulimit -c 0"-prop_checkBashisms58 = verify checkBashisms "#!/bin/sh\nulimit -c 0"+prop_checkBashisms57 = verifyNot checkBashisms "#!/bin/dash\nulimit -m unlimited"+prop_checkBashisms58 = verify checkBashisms "#!/bin/sh\nulimit -x unlimited" prop_checkBashisms59 = verify checkBashisms "#!/bin/sh\njobs -s" prop_checkBashisms60 = verifyNot checkBashisms "#!/bin/sh\njobs -p" prop_checkBashisms61 = verifyNot checkBashisms "#!/bin/sh\njobs -lp"@@ -174,7 +175,7 @@ prop_checkBashisms81 = verifyNot checkBashisms "#!/bin/dash\nhash -v" prop_checkBashisms82 = verifyNot checkBashisms "#!/bin/sh\nset -v +o allexport -o errexit -C" prop_checkBashisms83 = verifyNot checkBashisms "#!/bin/sh\nset --"-prop_checkBashisms84 = verify checkBashisms "#!/bin/sh\nset -o pipefail"+prop_checkBashisms84 = verifyNot checkBashisms "#!/bin/sh\nset -o pipefail" prop_checkBashisms85 = verify checkBashisms "#!/bin/sh\nset -B" prop_checkBashisms86 = verifyNot checkBashisms "#!/bin/dash\nset -o emacs" prop_checkBashisms87 = verify checkBashisms "#!/bin/sh\nset -o emacs"@@ -212,6 +213,39 @@ prop_checkBashisms119 = verify checkBashisms "#!/bin/busybox sh\nx='test'\n${x^^[t]}" -- SC3059 prop_checkBashisms120 = verify checkBashisms "#!/bin/sh\n[ x == y ]" prop_checkBashisms121 = verifyNot checkBashisms "#!/bin/sh\n# shellcheck shell=busybox\n[ x == y ]"+prop_checkBashisms122 = verifyNot checkBashisms "#!/bin/dash\n$'a'"+prop_checkBashisms123 = verifyNot checkBashisms "#!/bin/busybox sh\n$'a'"+prop_checkBashisms124 = verify checkBashisms "#!/bin/dash\ntype -p test"+prop_checkBashisms125 = verifyNot checkBashisms "#!/bin/busybox sh\ntype -p test"+prop_checkBashisms126 = verifyNot checkBashisms "#!/bin/busybox sh\nread -p foo -r bar"+prop_checkBashisms127 = verifyNot checkBashisms "#!/bin/busybox sh\necho -ne foo"+prop_checkBashisms128 = verify checkBashisms "#!/bin/dash\ntype -p test"+prop_checkBashisms129 = verify checkBashisms "#!/bin/sh\n[ -k /tmp ]"+prop_checkBashisms130 = verifyNot checkBashisms "#!/bin/dash\ntest -k /tmp"+prop_checkBashisms131 = verify checkBashisms "#!/bin/sh\n[ -o errexit ]"+prop_checkBashisms132 = verify checkBashisms "echo $\"hello\"" -- SC3004+prop_checkBashisms133 = verify checkBashisms "for ((;;)); do break; done" -- SC3005+prop_checkBashisms134 = verify checkBashisms "((var))" -- SC3006+prop_checkBashisms135 = verify checkBashisms "var=$[1 + 2]" -- SC3007+prop_checkBashisms136 = verify checkBashisms "select x; do :; done" -- SC3008+prop_checkBashisms137a = verify checkBashisms "echo {a,b}" -- SC3009+prop_checkBashisms137b = verify checkBashisms "echo {1..3}" -- SC3009+prop_checkBashisms138 = verify checkBashisms "[[ -z $var ]]" -- SC3010+prop_checkBashisms139 = verify checkBashisms "cat <<< foo" -- SC3011+prop_checkBashisms140a = verify checkBashisms "[ a '<' b ]" -- SC3012+prop_checkBashisms140b = verify checkBashisms "test a \\> b" -- SC3012+prop_checkBashisms141 = verify checkBashisms "echo $((2 ** 3))" -- SC3019+prop_checkBashisms142 = verify checkBashisms "make |& less" -- SC3029+prop_checkBashisms143 = verify checkBashisms "a=(foo bar)" -- SC3030+prop_checkBashisms144 = verify checkBashisms "coproc foo { :; }" -- SC3032+prop_checkBashisms145a = verify checkBashisms "#!/bin/sh\nf() { local i=; }" -- SC3043+prop_checkBashisms145b = verifyNot checkBashisms "#!/bin/dash\nf() { local i=; }" -- SC3043+prop_checkBashisms146 = verify checkBashisms "readarray < file" -- SC3044+prop_checkBashisms147 = verify checkBashisms "[ -R ref ]" -- SC3063+prop_checkBashisms148 = verify checkBashisms "[ -N file ]" -- SC3064+prop_checkBashisms149 = verify checkBashisms "[ -G file ]" -- SC3066+prop_checkBashisms150 = verify checkBashisms "[ -O file ]" -- SC3067+prop_checkBashisms151 = verifyNot checkBashisms "#!/bin/busybox sh\npwd | tee >(gzip > log.gz)" -- SC3001 checkBashisms = ForShell [Sh, Dash, BusyboxSh] $ \t -> do     params <- ask     kludge params t@@ -227,46 +261,27 @@         else warn id code $ "In POSIX sh, " ++ s ++ " undefined."     asStr = getLiteralString -    bashism (T_ProcSub id _ _) = warnMsg id 3001 "process substitution is"+    bashism (T_ProcSub id _ _) = unless isBusyboxSh $ warnMsg id 3001 "process substitution is"     bashism (T_Extglob id _ _) = warnMsg id 3002 "extglob is"-    bashism (T_DollarSingleQuoted id _) = warnMsg id 3003 "$'..' is"     bashism (T_DollarDoubleQuoted id _) = warnMsg id 3004 "$\"..\" is"     bashism (T_ForArithmetic id _ _ _ _) = warnMsg id 3005 "arithmetic for loops are"     bashism (T_Arithmetic id _) = warnMsg id 3006 "standalone ((..)) is"     bashism (T_DollarBracket id _) = warnMsg id 3007 "$[..] in place of $((..)) is"     bashism (T_SelectIn id _ _ _) = warnMsg id 3008 "select loops are"     bashism (T_BraceExpansion id _) = warnMsg id 3009 "brace expansion is"-    bashism (T_Condition id DoubleBracket _) =+    bashism (T_Condition id DoubleBracket _ _) =         unless isBusyboxSh $ warnMsg id 3010 "[[ ]] is"     bashism (T_HereString id _) = warnMsg id 3011 "here-strings are"-    bashism (TC_Binary id SingleBracket op _ _)-        | op `elem` [ "<", ">", "\\<", "\\>", "<=", ">=", "\\<=", "\\>="] =-            unless isDash $ warnMsg id 3012 $ "lexicographical " ++ op ++ " is"-    bashism (T_SimpleCommand id _ [asStr -> Just "test", lhs, asStr -> Just op, rhs])-        | op `elem` [ "<", ">", "\\<", "\\>", "<=", ">=", "\\<=", "\\>="] =-            unless isDash $ warnMsg id 3012 $ "lexicographical " ++ op ++ " is"-    bashism (TC_Binary id SingleBracket op _ _)-        | op `elem` [ "-ot", "-nt", "-ef" ] =-            unless isDash $ warnMsg id 3013 $ op ++ " is"-    bashism (T_SimpleCommand id _ [asStr -> Just "test", lhs, asStr -> Just op, rhs])-        | op `elem` [ "-ot", "-nt", "-ef" ] =-            unless isDash $ warnMsg id 3013 $ op ++ " is"-    bashism (TC_Binary id SingleBracket "==" _ _) =-        unless isBusyboxSh $ warnMsg id 3014 "== in place of = is"-    bashism (T_SimpleCommand id _ [asStr -> Just "test", lhs, asStr -> Just "==", rhs]) =-        unless isBusyboxSh $ warnMsg id 3014 "== in place of = is"-    bashism (TC_Binary id SingleBracket "=~" _ _) =-            warnMsg id 3015 "=~ regex matching is"-    bashism (T_SimpleCommand id _ [asStr -> Just "test", lhs, asStr -> Just "=~", rhs]) =-            warnMsg id 3015 "=~ regex matching is"-    bashism (TC_Unary id SingleBracket "-v" _) =-            warnMsg id 3016 "unary -v (in place of [ -n \"${var+x}\" ]) is"-    bashism (T_SimpleCommand id _ [asStr -> Just "test", asStr -> Just "-v", _]) =-            warnMsg id 3016 "unary -v (in place of [ -n \"${var+x}\" ]) is"-    bashism (TC_Unary id _ "-a" _) =-            warnMsg id 3017 "unary -a in place of -e is"-    bashism (T_SimpleCommand id _ [asStr -> Just "test", asStr -> Just "-a", _]) =-            warnMsg id 3017 "unary -a in place of -e is"++    bashism (TC_Binary id _ op _ _) =+        checkTestOp bashismBinaryTestFlags op id+    bashism (T_SimpleCommand id _ [asStr -> Just "test", lhs, asStr -> Just op, rhs]) =+        checkTestOp bashismBinaryTestFlags op id+    bashism (TC_Unary id _ op _) =+        checkTestOp bashismUnaryTestFlags op id+    bashism (T_SimpleCommand id _ [asStr -> Just "test", asStr -> Just op, _]) =+        checkTestOp bashismUnaryTestFlags op id+     bashism (TA_Unary id op _)         | op `elem` [ "|++", "|--", "++|", "--|"] =             warnMsg id 3018 $ filter (/= '|') op ++ " is"@@ -321,8 +336,12 @@      bashism t@(T_SimpleCommand _ _ (cmd:arg:_))         | t `isCommand` "echo" && argString `matches` flagRegex =-            if isDash+            if isBusyboxSh             then+                unless (argString `matches` busyboxFlagRegex) $+                    warnMsg (getId arg) 3036 "echo flags besides -n and -e"+            else if isDash+            then                 when (argString /= "-n") $                     warnMsg (getId arg) 3036 "echo flags besides -n"             else@@ -330,6 +349,7 @@       where           argString = concat $ oversimplify arg           flagRegex = mkRegex "^-[eEsn]+$"+          busyboxFlagRegex = mkRegex "^-[en]+$"      bashism t@(T_SimpleCommand _ _ (cmd:arg:_))         | getLiteralString cmd == Just "exec" && "-" `isPrefixOf` concat (oversimplify arg) =@@ -364,7 +384,7 @@         checkFlags (flag@(fid, flag'):rest)             | startsOption flag' = do                 unless (flag' `matches` validFlagsRegex) $-                  forM_ (tail flag') $ \letter ->+                  forM_ (drop 1 flag') $ \letter ->                     when (letter `notElem` optionsSet) $                       warnMsg fid 3041 $ "set flag " <> ('-':letter:" is")                 checkOptions rest@@ -384,8 +404,8 @@         beginsWithDoubleDash = (`matches` mkRegex "^--.+$")         longOptions          = Set.fromList             [ "allexport", "errexit", "ignoreeof", "monitor", "noclobber"-            , "noexec", "noglob", "nolog", "notify" , "nounset", "verbose"-            , "vi", "xtrace" ]+            , "noexec", "noglob", "nolog", "notify" , "nounset", "pipefail"+            , "verbose", "vi", "xtrace" ]      bashism t@(T_SimpleCommand id _ (cmd:rest)) =         let name = fromMaybe "" $ getCommandName t@@ -443,11 +463,16 @@             ("hash", Just $ if isDash then ["r", "v"] else ["r"]),             ("jobs", Just ["l", "p"]),             ("printf", Just []),-            ("read", Just $ if isDash then ["r", "p"] else ["r"]),+            ("read", Just $ if isDash || isBusyboxSh then ["r", "p"] else ["r"]),             ("readonly", Just ["p"]),             ("trap", Just []),-            ("type", Just []),-            ("ulimit", if isDash then Nothing else Just ["f"]),+            ("type", Just $ if isBusyboxSh then ["p"] else []),+            ("ulimit",+              Just $+                if isDash+                  then ["H", "S", "a", "c", "d", "f", "l", "m", "n", "p", "r", "s", "t", "v", "w"]+                  else ["H", "S", "a", "c", "d", "f", "n", "s", "t", "v"] -- POSIX.1-2024+            ),             ("umask", Just ["S"]),             ("unset", Just ["f", "v"]),             ("wait", Just [])@@ -480,13 +505,18 @@         -- for shell identification.         "OSTYPE", "MACHTYPE", "HOSTTYPE", "HOSTNAME",         "DIRSTACK", "EUID", "UID", "SHLVL", "PIPESTATUS", "SHELLOPTS",-        "_", "BASHOPTS", "BASHPID", "BASH_ALIASES", "BASH_ARGC",+        "_", "BASH", "BASHOPTS", "BASHPID", "BASH_ALIASES", "BASH_ARGC",         "BASH_ARGV", "BASH_ARGV0", "BASH_CMDS", "BASH_COMMAND",-        "BASH_EXECUTION_STRING", "BASH_LINENO", "BASH_REMATCH", "BASH_SOURCE",-        "BASH_SUBSHELL", "BASH_VERSINFO", "EPOCHREALTIME", "EPOCHSECONDS",-        "FUNCNAME", "GROUPS", "MACHTYPE", "MAPFILE"+        "BASH_EXECUTION_STRING", "BASH_LINENO", "BASH_LOADABLES_PATH",+        "BASH_REMATCH", "BASH_SOURCE", "BASH_SUBSHELL", "BASH_VERSINFO",+        "COMP_CWORD", "COMP_KEY", "COMP_LINE", "COMP_POINT", "COMP_TYPE",+        "COMP_WORDBREAKS", "COMP_WORDS", "COPROC", "FUNCNAME", "GROUPS",+        "HISTCMD", "MAPFILE"         ]-    bashDynamicVars = [ "RANDOM", "SECONDS" ]+    bashDynamicVars = [+        "BASH_MONOSECONDS", "EPOCHREALTIME", "EPOCHSECONDS", "RANDOM",+        "SECONDS", "SRANDOM"+        ]     dashVars = [ "_" ]     isBashVariable var =         (var `elem` bashDynamicVars@@ -498,6 +528,50 @@                 Assignment (_, _, name, _) -> name == var                 _ -> False +    checkTestOp table op id = sequence_ $ do+        (code, shells, msg) <- Map.lookup op table+        guard . not $ shellType params `elem` shells+        return $ warnMsg id code (msg op)+++buildTestFlagMap list = Map.fromList $ concatMap (\(x,y) -> map (\c -> (c,y)) x) list+bashismBinaryTestFlags = buildTestFlagMap [+    -- ([list of applicable flags],+    --     (error code, exempt shells, message builder :: String -> String)),+    --+    -- Distinct error codes allow the wiki to give more helpful, targeted+    -- information.+    (["<", ">", "\\<", "\\>", "<=", ">=", "\\<=", "\\>="],+        (3012, [Dash, BusyboxSh], \op -> "lexicographical " ++ op ++ " is")),+    (["=="],+        (3014, [BusyboxSh], \op -> op ++ " in place of = is")),+    (["=~"],+        (3015, [], \op -> op ++ " regex matching is")),++    ([], (0,[],const ""))+  ]+bashismUnaryTestFlags = buildTestFlagMap [+    (["-v"],+        (3016, [], \op -> "test " ++ op ++ " (in place of [ -n \"${var+x}\" ]) is")),+    (["-a"],+        (3017, [], \op -> "unary " ++ op ++ " in place of -e is")),+    (["-o"],+        (3062, [], \op -> "test " ++ op ++ " to check options is")),+    (["-R"],+        (3063, [], \op -> "test " ++ op ++ " and namerefs in general are")),+    (["-N"],+        (3064, [], \op -> "test " ++ op ++ " is")),+    (["-k"],+        (3065, [Dash, BusyboxSh], \op -> "test " ++ op ++ " is")),+    (["-G"],+        (3066, [Dash, BusyboxSh], \op -> "test " ++ op ++ " is")),+    (["-O"],+        (3067, [Dash, BusyboxSh], \op -> "test " ++ op ++ " is")),++    ([], (0,[],const ""))+  ]++ prop_checkEchoSed1 = verify checkEchoSed "FOO=$(echo \"$cow\" | sed 's/foo/bar/g')" prop_checkEchoSed1b = verify checkEchoSed "FOO=$(sed 's/foo/bar/g' <<< \"$cow\")" prop_checkEchoSed2 = verify checkEchoSed "rm $(echo $cow | sed -e 's,foo,bar,')"@@ -636,6 +710,23 @@         T_Banged id _ ->             err id 2326 "! is not allowed in the middle of pipelines. Use command group as in cmd | { ! cmd; } if necessary."         _ -> return ()+++prop_checkNegatedUnaryOps1 = verify checkNegatedUnaryOps "[ ! -o braceexpand ]"+prop_checkNegatedUnaryOps2 = verifyNot checkNegatedUnaryOps "[ -o braceexpand ]"+prop_checkNegatedUnaryOps3 = verifyNot checkNegatedUnaryOps "[[ ! -o braceexpand ]]"+prop_checkNegatedUnaryOps4 = verifyNot checkNegatedUnaryOps "! [ -o braceexpand ]"+prop_checkNegatedUnaryOps5 = verify checkNegatedUnaryOps "[ ! -a file ]"+checkNegatedUnaryOps = ForShell [Bash] f+  where+    f token = case token of+        TC_Unary id SingleBracket "!" (TC_Unary _ _ op _) | op `elem` ["-a", "-o"] ->+            err id 2332 $ msg op+        _ -> return ()++    msg "-o" = "[ ! -o opt ] is always true because -o becomes logical OR. Use [[ ]] or ! [ -o opt ]."+    msg "-a" = "[ ! -a file ] is always true because -a becomes logical AND. Use -e instead."+    msg _ = pleaseReport "unhandled negated unary message"  return [] runTests =  $( [| $(forAllProperties) (quickCheckWithResult (stdArgs { maxSuccess = 1 }) ) |])
src/ShellCheck/Data.hs view
@@ -1,6 +1,10 @@ module ShellCheck.Data where +import ShellCheck.AST (Annotation(ShellOverride)) import ShellCheck.Interface+import ShellCheck.Prelude (headOrDefault)+import Data.List (isSuffixOf)+import Data.Maybe (listToMaybe) import Data.Version (showVersion)  @@ -28,6 +32,12 @@     -- Generic     "", "_", "rest", "REST", +    -- POSIX+    "CDPATH", "ENV", "FCEDIT", "HISTFILE", "HISTSIZE", "HOME", "IFS", "LANG",+    "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY",+    "LC_NUMERIC", "LC_TIME", "MAIL", "MAILCHECK", "MAILPATH", "OLDPWD",+    "OPTARG", "OPTIND", "PATH", "PWD",+     -- Bash     "BASH", "BASHOPTS", "BASHPID", "BASH_ALIASES", "BASH_ARGC",     "BASH_ARGV", "BASH_ARGV0", "BASH_CMDS", "BASH_COMMAND",@@ -36,24 +46,20 @@     "BASH_VERSION", "COMP_CWORD", "COMP_KEY", "COMP_LINE", "COMP_POINT",     "COMP_TYPE", "COMP_WORDBREAKS", "COMP_WORDS", "COPROC", "DIRSTACK",     "EPOCHREALTIME", "EPOCHSECONDS", "EUID", "FUNCNAME", "GROUPS", "HISTCMD",-    "HOSTNAME", "HOSTTYPE", "LINENO", "MACHTYPE", "MAPFILE", "OLDPWD",-    "OPTARG", "OPTIND", "OSTYPE", "PIPESTATUS", "PPID", "PWD", "RANDOM",-    "READLINE_ARGUMENT", "READLINE_LINE", "READLINE_MARK", "READLINE_POINT",-    "REPLY", "SECONDS", "SHELLOPTS", "SHLVL", "SRANDOM", "UID", "BASH_COMPAT",-    "BASH_ENV", "BASH_XTRACEFD", "CDPATH", "CHILD_MAX", "COLUMNS",-    "COMPREPLY", "EMACS", "ENV", "EXECIGNORE", "FCEDIT", "FIGNORE",-    "FUNCNEST", "GLOBIGNORE", "HISTCONTROL", "HISTFILE", "HISTFILESIZE",-    "HISTIGNORE", "HISTSIZE", "HISTTIMEFORMAT", "HOME", "HOSTFILE", "IFS",-    "IGNOREEOF", "INPUTRC", "INSIDE_EMACS", "LANG", "LC_ALL", "LC_COLLATE",-    "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME",-    "LINES", "MAIL", "MAILCHECK", "MAILPATH", "OPTERR", "PATH",-    "POSIXLY_CORRECT", "PROMPT_COMMAND", "PROMPT_DIRTRIM", "PS0", "PS1",-    "PS2", "PS3", "PS4", "SHELL", "TIMEFORMAT", "TMOUT", "TMPDIR",-    "auto_resume", "histchars",+    "HOSTNAME", "HOSTTYPE", "MACHTYPE", "MAPFILE", "OSTYPE", "PIPESTATUS",+    "RANDOM", "READLINE_ARGUMENT", "READLINE_LINE", "READLINE_MARK",+    "READLINE_POINT", "REPLY", "SECONDS", "SHELLOPTS", "SHLVL", "SRANDOM",+    "UID", "BASH_COMPAT", "BASH_ENV", "BASH_XTRACEFD", "CHILD_MAX", "COLUMNS",+    "COMPREPLY", "EMACS", "EXECIGNORE", "FIGNORE", "FUNCNEST", "GLOBIGNORE",+    "HISTCONTROL", "HISTFILESIZE", "HISTIGNORE", "HISTTIMEFORMAT", "HOSTFILE",+    "IGNOREEOF", "INPUTRC", "INSIDE_EMACS", "LINES", "OPTERR",+    "POSIXLY_CORRECT", "PROMPT_COMMAND", "PROMPT_DIRTRIM", "PS0", "PS1", "PS2",+    "PS3", "PS4", "SHELL", "TIMEFORMAT", "TMOUT", "BASH_MONOSECONDS",+    "BASH_TRAPSIG", "GLOBSORT", "auto_resume", "histchars",      -- Other     "USER", "TZ", "TERM", "LOGNAME", "LD_LIBRARY_PATH", "LANGUAGE", "DISPLAY",-    "HOSTNAME", "KRB5CCNAME", "XAUTHORITY"+    "HOSTNAME", "KRB5CCNAME", "LINENO", "PPID", "TMPDIR", "XAUTHORITY"      -- Ksh     , ".sh.version"@@ -75,7 +81,7 @@     "EPOCHREALTIME", "EPOCHSECONDS", "LINENO", "OPTIND", "PPID", "RANDOM",     "READLINE_ARGUMENT", "READLINE_MARK", "READLINE_POINT", "SECONDS",     "SHELLOPTS", "SHLVL", "SRANDOM", "UID", "COLUMNS", "HISTFILESIZE",-    "HISTSIZE", "LINES"+    "HISTSIZE", "LINES", "BASH_MONOSECONDS", "BASH_TRAPSIG"      -- shflags     , "FLAGS_ERROR", "FLAGS_FALSE", "FLAGS_TRUE"@@ -100,31 +106,31 @@     "compress", "continue", "cp", "crontab", "csplit", "ctags", "cut",     "cxref", "date", "dd", "delta", "df", "diff", "dirname", "dot",     "du", "echo", "ed", "env", "eval", "ex", "exec", "exit", "expand",-    "export", "expr", "fc", "fg", "file", "find", "fold", "fort77",-    "fuser", "gencat", "get", "getconf", "getopts", "grep", "hash",+    "export", "expr", "fc", "fg", "file", "find", "fold", "fuser",+    "gencat", "get", "getconf", "getopts", "gettext", "grep", "hash",     "head", "iconv", "ipcrm", "ipcs", "jobs", "join", "kill", "lex",     "link", "ln", "locale", "localedef", "logger", "logname", "lp",     "ls", "m4", "mailx", "make", "man", "mesg", "mkdir", "mkfifo",-    "more", "mv", "newgrp", "nice", "nl", "nm", "nohup", "od", "paste",-    "patch", "pathchk", "pax", "pr", "printf", "prs", "ps", "pwd",-    "qalter", "qdel", "qhold", "qmove", "qmsg", "qrerun", "qrls",-    "qselect", "qsig", "qstat", "qsub", "read", "readonly", "renice",-    "return", "rm", "rmdel", "rmdir", "sact", "sccs", "sed", "set",-    "sh", "shift", "sleep", "sort", "split", "strings", "strip", "stty",-    "tabs", "tail", "talk", "tee", "test", "time", "times", "touch",-    "tput", "tr", "trap", "tsort", "tty", "type", "ulimit", "umask",-    "unalias", "uname", "uncompress", "unexpand", "unget", "uniq",-    "unlink", "unset", "uucp", "uudecode", "uuencode", "uustat", "uux",-    "val", "vi", "wait", "wc", "what", "who", "write", "xargs", "yacc",-    "zcat"+    "more", "msgfmt", "mv", "newgrp", "ngettext", "nice", "nl", "nm",+    "nohup", "od", "paste", "patch", "pathchk", "pax", "pr", "printf",+    "prs", "ps", "pwd", "read", "readlink", "readonly", "realpath",+    "renice", "return", "rm", "rmdel", "rmdir", "sact", "sccs", "sed",+    "set", "sh", "shift", "sleep", "sort", "split", "strings", "strip",+    "stty", "tabs", "tail", "talk", "tee", "test", "time", "timeout",+    "times", "touch", "tput", "tr", "trap", "tsort", "tty", "type",+    "ulimit", "umask", "unalias", "uname", "uncompress", "unexpand",+    "unget", "uniq", "unlink", "unset", "uucp", "uudecode", "uuencode",+    "uustat", "uux", "val", "vi", "wait", "wc", "what", "who", "write",+    "xargs", "xgettext", "yacc", "zcat"   ]  nonReadingCommands = [     "alias", "basename", "bg", "cal", "cd", "chgrp", "chmod", "chown",     "cp", "du", "echo", "export", "fg", "fuser", "getconf",     "getopt", "getopts", "ipcrm", "ipcs", "jobs", "kill", "ln", "ls",-    "locale", "mv", "printf", "ps", "pwd", "renice", "rm", "rmdir",-    "set", "sleep", "touch", "trap", "ulimit", "unalias", "uname"+    "locale", "mv", "printf", "ps", "pwd", "readlink", "realpath",+    "renice", "rm", "rmdir", "set", "sleep", "touch", "trap", "ulimit",+    "unalias", "uname"     ]  sampleWords = [@@ -150,6 +156,10 @@     "-o", "-v", "-R"   ] +supportedShellDialects = [+    "sh", "bash", "dash", "ksh", "busybox"+  ]+ shellForExecutable :: String -> Maybe Shell shellForExecutable name =     case name of@@ -164,9 +174,29 @@         "ksh"   -> return Ksh         "ksh88" -> return Ksh         "ksh93" -> return Ksh+        "oksh"  -> return Ksh         _ -> Nothing +shellFromAnnotations :: [Annotation] -> String -> Maybe Shell+shellFromAnnotations annotations executable =+    shellForExecutable $ headOrDefault executable [s | ShellOverride s <- annotations]++shellFromFilename :: String -> Maybe Shell+shellFromFilename filename = listToMaybe candidates+  where+    shellExtensions = [(".ksh", Ksh)+                      ,(".bash", Bash)+                      ,(".bats", Bash)+                      ,(".dash", Dash)+                      ,(".envrc", Bash)]+                      -- The `.sh` is too generic to determine the shell:+                      -- We fallback to Bash in this case and emit SC2148 if there is no shebang+    candidates =+        [sh | (ext,sh) <- shellExtensions, ext `isSuffixOf` filename]+ flagsForRead = "sreu:n:N:i:p:a:t:" flagsForMapfile = "d:n:O:s:u:C:c:t"  declaringCommands = ["local", "declare", "export", "readonly", "typeset", "let"]++privilegeElevationCommands = ["sudo", "doas", "run0"]
src/ShellCheck/Debug.hs view
@@ -74,7 +74,7 @@  -} -module ShellCheck.Debug () where+module ShellCheck.Debug where  import ShellCheck.Analyzer import ShellCheck.AST@@ -117,7 +117,8 @@ cfgParams :: CFGParameters cfgParams = CFGParameters {     cfLastpipe = False,-    cfPipefail = False+    cfPipefail = False,+    cfSourceAsBoundary = False }  -- An example script to play with
+ src/ShellCheck/EditorConfig.hs view
@@ -0,0 +1,468 @@+{-+    Copyright 2012-2024 Vidar Holen++    This file is part of ShellCheck.+    https://www.shellcheck.net++    ShellCheck is free software: you can redistribute it and/or modify+    it under the terms of the GNU General Public License as published by+    the Free Software Foundation, either version 3 of the License, or+    (at your option) any later version.++    ShellCheck is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <https://www.gnu.org/licenses/>.+-}++{-# LANGUAGE TemplateHaskell #-}+-- Minimal support for reading shellcheck directives from EditorConfig+-- style files (https://editorconfig.org/). Only the `shellcheck.*` keys+-- of sections whose glob matches the file being checked are extracted,+-- and turned into the same "key=value" directive syntax that is used in+-- .shellcheckrc files.+module ShellCheck.EditorConfig (parseEditorConfig, isEditorConfigRoot, invalidRootLines, invalidDirectiveLines, editorConfigDirectives, globToRegexString, runTests) where++import Data.Char+import Data.List+import Data.Maybe++import ShellCheck.Data (shellForExecutable)+import ShellCheck.Regex++import Test.QuickCheck++-- Given the contents of an EditorConfig style file and the name of the+-- file being checked, return the shellcheck directives (as a+-- "key=value\n" delimited blob, suitable for feeding into the same+-- parser as .shellcheckrc) found in matching sections.+--+-- As per the EditorConfig spec, files are read top to bottom and+-- properties from later sections override those from earlier ones+-- (for the same key), so on conflicts the last matching section wins.+parseEditorConfig :: String -> FilePath -> String+parseEditorConfig contents name =+    renderDirectives . lastWins . mapMaybe usable $ allDirectives name sections+  where+    -- Render each directive at its original line in the config file, so+    -- that any parse error (SC1134) is reported at the correct line.+    renderDirectives = snd . foldl step (0, "")+    step (prevLine, out) (line, key, value) =+        (line, out ++ replicate (line - prevLine - 1) '\n' ++ key ++ "=" ++ value ++ "\n")++    -- Keep only the last occurrence of each key, preserving the+    -- relative order of the remaining (first-seen) entries.+    lastWins = reverse . nubBy (\a b -> keyOf a == keyOf b) . reverse+      where+        keyOf (_, key, _) = key++    usable (line, key, value) =+        if isUsableDirective key value+            then Just (line, key, value)+            else Nothing++    ls = lines contents+    sections = splitSections 1 ls++    splitSections _ [] = []+    splitSections n (l:rest) =+        case parseHeader l of+            Just pat ->+                let (body, rest') = break (isJust . parseHeader) rest+                in (pat, zip [n+1..] body) : splitSections (n + 1 + length body) rest'+            Nothing -> splitSections (n+1) rest++    parseHeader l =+        let t = trim (dropLineComment l)+        in case t of+            ('[':cs@(_:_)) | last cs == ']' -> Just (init cs)+            _ -> Nothing++    -- All 'shellcheck.*' directives (as (line, key, value) tuples) found+    -- in sections whose glob matches the file being checked.+    allDirectives name = concatMap (sectionDirectives name)++    sectionDirectives name (pat, body) =+        if matchesGlob pat name+        then mapMaybe toDirectivePair body+        else []++    toDirectivePair (line, l) =+        case break (== '=') (trim (dropLineComment l)) of+            (key, '=':value) ->+                let key' = trim key+                    value' = trim value+                in if "shellcheck." `isPrefixOf` key'+                    then Just (line, drop (length "shellcheck.") key', value')+                    else Nothing+            _ -> Nothing++    -- Only emit directives that the .shellcheckrc parser can handle+    -- unambiguously. Unknown shells (e.g. 'shellcheck.shell=zsh') would+    -- otherwise silently suppress the SC2148 "unknown shell" warning, so+    -- they are dropped here and reported via invalidDirectiveLines.+    -- Values containing '#' or ';' anywhere (not just at the start) are+    -- also dropped and reported: EditorConfig has no inline comments, so+    -- such a value is otherwise silently truncated by the .shellcheckrc+    -- parser's trailing-comment handling (e.g. both 'disable=#abc' and+    -- 'disable=SC2148 #abc' would silently lose the part from '#'+    -- onwards). Empty values for other keys are simply skipped (no-op):+    -- the rc parser would silently accept them anyway.+    isUsableDirective "shell" value = null value || isJust (shellForExecutable value)+    isUsableDirective _ value = not (null value) && not (hasCommentMarker value)++    hasCommentMarker = any (`elem` "#;")++-- Returns the 1-based line numbers of invalid 'shellcheck.*' directives,+-- i.e.:+--   * 'shellcheck.shell=<x>' where <x> is a non-empty, unknown shell+--     (e.g. 'zsh'), which would otherwise silently suppress the SC2148+--     "unknown shell" warning;+--   * any 'shellcheck.<key>=<value>' whose (trimmed) value contains '#'+--     or ';' anywhere, since EditorConfig does not allow inline comments+--     and such a value is otherwise silently truncated by the+--     .shellcheckrc parser's trailing-comment handling (e.g. both+--     'disable=#abc' and 'disable=SC2148 #abc' would silently lose the+--     part from '#' onwards). Plain empty values are not reported here:+--     they are simply no-ops.+-- Only directives in sections whose glob matches the file are reported.+invalidDirectiveLines :: String -> FilePath -> [Int]+invalidDirectiveLines contents name =+    [ line | (line, key, value) <- allDirectives name sections+           , isInvalidDirective key value ]+  where+    isInvalidDirective "shell" value = not (null value) && isNothing (shellForExecutable value)+    isInvalidDirective _ value = hasCommentMarker value++    hasCommentMarker = any (`elem` "#;")++    sections = splitSections 1 (lines contents)++    splitSections _ [] = []+    splitSections n (l:rest) =+        case parseHeader l of+            Just pat ->+                let (body, rest') = break (isJust . parseHeader) rest+                in (pat, zip [n+1..] body) : splitSections (n + 1 + length body) rest'+            Nothing -> splitSections (n+1) rest++    parseHeader l =+        let t = trim (dropLineComment l)+        in case t of+            ('[':cs@(_:_)) | last cs == ']' -> Just (init cs)+            _ -> Nothing++    allDirectives name = concatMap (sectionDirectives name)++    sectionDirectives name (pat, body) =+        if matchesGlob pat name+        then mapMaybe toDirectivePair body+        else []++    toDirectivePair (line, l) =+        case break (== '=') (trim (dropLineComment l)) of+            (key, '=':value) ->+                let key' = trim key+                    value' = trim value+                in if "shellcheck." `isPrefixOf` key'+                    then Just (line, drop (length "shellcheck.") key', value')+                    else Nothing+            _ -> Nothing++-- Build the directive blob contributed by a single EditorConfig file for+-- the given file being checked. Returns Nothing if the file contributes+-- nothing (no matching section, or only empty values). Returns a blob of+-- "key=value\n" directives when the matching sections are valid, or a+-- single rejected line at the position of any invalid 'shellcheck.*'+-- directive so that the .shellcheckrc parser reports it as SC1134.+editorConfigDirectives :: String -> FilePath -> Maybe String+editorConfigDirectives contents name =+    let badLines = invalidDirectiveLines contents name+    in if not (null badLines)+        then Just . unlines $ map rejectedLine (nub (sort badLines))+        else let result = parseEditorConfig contents name+             in if null result then Nothing else Just result+  where+    rejectedLine n = replicate (n - 1) '\n' ++ "invalid editorconfig value"++-- Does the top-level (pre-section) part of an EditorConfig file+-- declare "root = true"? Per the spec, this stops the search for+-- further EditorConfig files in parent directories.+isEditorConfigRoot :: String -> Bool+isEditorConfigRoot contents =+    any (== Just "true") . map rootValue $ preSectionLines contents+  where+    isSectionHeader l =+        case trim (dropLineComment l) of+            ('[':cs@(_:_)) -> last cs == ']'+            _ -> False+    preSectionLines = takeWhile (not . isSectionHeader) . lines++    rootValue l =+        case break (== '=') (trim (dropLineComment l)) of+            (key, '=':value) | map toLower (trim key) == "root" ->+                Just (map toLower (trim value))+            _ -> Nothing++-- Returns the 1-based line numbers of invalid 'root' declarations,+-- i.e. root values other than true/false (such as 'root =').+invalidRootLines :: String -> [Int]+invalidRootLines contents =+    [ n | (n, l) <- zip [1..] (preSectionLines contents)+        , case rootValue l of+            Just value -> value `notElem` ["true", "false"]+            Nothing -> False ]+  where+    isSectionHeader l =+        case trim (dropLineComment l) of+            ('[':cs@(_:_)) -> last cs == ']'+            _ -> False+    preSectionLines = takeWhile (not . isSectionHeader) . lines++    rootValue l =+        case break (== '=') (trim (dropLineComment l)) of+            (key, '=':value) | map toLower (trim key) == "root" ->+                Just (map toLower (trim value))+            _ -> Nothing++-- EditorConfig does not allow inline comments; '#' and ';' starting+-- on the first non-whitespace character denote a full-line comment.+-- Lines not starting with '#' or ';' must be returned verbatim.+dropLineComment l =+    case dropWhile isSpace l of+        ('#':_) -> ""+        (';':_) -> ""+        _       -> l++trim :: String -> String+trim = dropWhileEnd isSpace . dropWhile isSpace++-- Does the (relative path of the) file match the given EditorConfig glob?+matchesGlob :: String -> FilePath -> Bool+matchesGlob pattern name =+    name `matches` mkRegex (globToRegexString pattern)++-- Translate an EditorConfig glob pattern into an anchored regex string.+-- Per the spec, patterns without a path separator are matched against+-- the file at any depth (as if prefixed with "**/").+globToRegexString :: String -> String+globToRegexString pattern = "^" ++ prefix ++ go pattern ++ "$"+  where+    prefix = if '/' `elem` pattern then "" else "(.*/)?"++    go [] = ""+    go ('*':'*':rest) = ".*" ++ go rest+    go ('*':rest) = "[^/]*" ++ go rest+    go ('?':rest) = "[^/]" ++ go rest+    go ('[':rest) =+        let (cls, rest') = break (== ']') rest+        in case rest' of+            (']':rest'') -> "[" ++ translateClass cls ++ "]" ++ go rest''+            _ -> "\\[" ++ go rest+    go ('{':rest) =+        case findMatchingBrace rest of+            Just (body, rest'') ->+                buildAlternation (map go (braceAlternatives body)) ++ go rest''+            _ -> "\\{" ++ go rest+    go (c:rest)+        | c `elem` regexSpecials = ['\\', c] ++ go rest+        | otherwise = c : go rest++    regexSpecials = ".\\+()^$|"++    translateClass ('!':cs) = '^' : escapeClass cs+    translateClass cs = escapeClass cs+    escapeClass = concatMap (\c -> if c == '\\' then "\\\\" else [c])++    -- Scan past a balanced '{' ... '}' pair, returning the contents of+    -- the braces (with any nested braces verbatim) and the remainder.+    -- Returns Nothing if the braces are unbalanced.+    findMatchingBrace = goBrace 1 ""+      where+        goBrace _ _ "" = Nothing+        goBrace d acc (c:cs)+            | c == '}' =+                if d == 1 then Just (reverse acc, cs)+                else goBrace (d - 1) (c:acc) cs+            | c == '{' = goBrace (d + 1) (c:acc) cs+            | otherwise = goBrace d (c:acc) cs++    -- Wrap a list of regex alternatives in an anchored group. Empty+    -- alternatives are handled so the result is always a valid regex:+    --   * all empty        -> "" (the whole group matches the empty string)+    --   * some empty       -> "(a|b)?" (the group is optional)+    --   * none empty       -> "(a|b|c)"+    buildAlternation alts+        | all null alts = ""+        | any null alts = "(" ++ intercalate "|" (filter (not . null) alts) ++ ")?"+        | otherwise = "(" ++ intercalate "|" alts ++ ")"++    -- Expand EditorConfig brace alternatives. Besides the comma+    -- separated form, EditorConfig supports numeric ranges like+    -- '{1..3}' which match any integer in the range. Commas inside+    -- nested braces (e.g. 'ba{r,z}') are not treated as separators.+    braceAlternatives body =+        case break (== '.') body of+            (fromStr, '.':'.':toStr)+                | Just from <- readInt fromStr+                , Just to <- readInt toStr ->+                    map show $+                        if from < to+                        then [from..to]+                        else []+            _ -> splitTopLevelCommas body++    -- Split on commas, but ignore commas that appear inside nested+    -- '{...}' pairs so that 'a,b{c,d}' yields ["a", "b{c,d}"].+    splitTopLevelCommas = go 0 ""+      where+        go _ acc "" = [reverse acc]+        go d acc (c:cs)+            | c == '{' = go (d + 1) (c:acc) cs+            | c == '}' = go (max 0 (d - 1)) (c:acc) cs+            | c == ',' && d == 0 = reverse acc : go 0 "" cs+            | otherwise = go d (c:acc) cs++    readInt s =+        case reads s :: [(Int, String)] of+            [(n, "")] -> Just n+            _ -> Nothing++prop_globStar = matchesGlob "*.ebuild" "foo.ebuild"+prop_globBraceExt = matchesGlob "*.{ebuild,eclass}" "foo.eclass"+prop_globBraceExt2 = matchesGlob "*.{ebuild,eclass}" "foo.ebuild"+prop_globBraceName = matchesGlob "{PKGBUILD,APKBUILD}" "PKGBUILD"+prop_globBraceName2 = matchesGlob "{PKGBUILD,APKBUILD}" "APKBUILD"+prop_globNoMatch = not $ matchesGlob "*.ebuild" "foo.txt"+prop_globQuestion = matchesGlob "foo?.sh" "food.sh"+prop_globClass = matchesGlob "foo[0-9].sh" "foo1.sh"+prop_globClassNeg = not $ matchesGlob "foo[!0-9].sh" "foo1.sh"+-- Patterns without a path separator should match at any depth.+prop_globAnyDepth = matchesGlob "*.sh" "sub/dir/foo.sh"+prop_globAnyDepthPlain = matchesGlob "foo" "sub/foo"+-- Patterns with a path separator are only matched against the full+-- relative path.+prop_globWithSlashNoMatch = not $ matchesGlob "sub/*.sh" "other/foo.sh"+prop_globWithSlashMatch = matchesGlob "sub/*.sh" "sub/foo.sh"+-- Numeric range expansion+prop_globRange = matchesGlob "file{1..3}.sh" "file2.sh"+prop_globRangeStart = matchesGlob "file{1..3}.sh" "file1.sh"+prop_globRangeEnd = matchesGlob "file{1..3}.sh" "file3.sh"+prop_globRangeNoMatch = not $ matchesGlob "file{1..3}.sh" "file4.sh"+prop_globRangeNegative = matchesGlob "file{-2..0}.sh" "file-1.sh"+prop_globRangeDescending = not $ matchesGlob "file{3..1}.sh" "file2.sh"+prop_globLiteralDots = not $ matchesGlob "file{1..3}.sh" "file1..3.sh"+-- Empty brace alternatives (e.g. 'foo{,bar}') make the group optional:+-- 'foo' and 'foobar' both match.+prop_globBraceEmptyAlt = matchesGlob "foo{,bar}" "foo"+prop_globBraceEmptyAlt2 = matchesGlob "foo{,bar}" "foobar"+prop_globBraceEmptyAltNoMatch = not $ matchesGlob "foo{,bar}" "foobaz"+-- Nested braces: '{foo,ba{r,z}}' matches foo, bar and baz.+prop_globBraceNested1 = matchesGlob "{foo,ba{r,z}}" "foo"+prop_globBraceNested2 = matchesGlob "{foo,ba{r,z}}" "bar"+prop_globBraceNested3 = matchesGlob "{foo,ba{r,z}}" "baz"+prop_globBraceNestedNoMatch = not $ matchesGlob "{foo,ba{r,z}}" "baq"++prop_parseEditorConfig1 =+    parseEditorConfig "[*.{ebuild,eclass}]\nshellcheck.shell=bash\nshellcheck.disable=SC2034\n" "foo.ebuild"+        == "\nshell=bash\ndisable=SC2034\n"+prop_parseEditorConfig2 =+    parseEditorConfig "[*.{ebuild,eclass}]\nshellcheck.shell=bash\n" "foo.txt" == ""+prop_parseEditorConfig3 =+    parseEditorConfig "[{PKGBUILD,APKBUILD}]\nshellcheck.disable=SC2034\n" "PKGBUILD" == "\ndisable=SC2034\n"+prop_parseEditorConfig4 =+    parseEditorConfig "root = true\n[*.sh]\nindent_style = space\nshellcheck.shell=bash\n" "foo.sh"+        == "\n\n\nshell=bash\n"+-- A later, more specific section overrides an earlier, more general+-- one for the same key.+prop_parseEditorConfig5 =+    parseEditorConfig "[*]\nshellcheck.shell=sh\n\n[foo]\nshellcheck.shell=bash\n" "foo"+        == "\n\n\n\nshell=bash\n"+-- Non-conflicting keys from earlier and later sections are all kept.+prop_parseEditorConfig6 =+    parseEditorConfig "[*]\nshellcheck.shell=sh\n\n[foo]\nshellcheck.disable=SC2034\n" "foo"+        == "\nshell=sh\n\n\ndisable=SC2034\n"+-- An unsupported shell is not emitted as a usable directive; instead its+-- line is reported via invalidDirectiveLines so the caller can reject it.+prop_parseEditorConfigUnknownShell =+    parseEditorConfig "[*]\nshellcheck.shell=zsh\n" "foo" == ""+prop_parseEditorConfigEmptyShell =+    parseEditorConfig "[*]\nshellcheck.shell=\n" "foo" == "\nshell=\n"+prop_parseEditorConfigEmptyDisable =+    parseEditorConfig "[*]\nshellcheck.disable=\n" "foo" == ""+-- A '#' embedded anywhere in the value (not just at the start) makes it+-- invalid too, since EditorConfig has no inline comments and the+-- .shellcheckrc parser would otherwise silently truncate it at the '#'.+prop_parseEditorConfigEmbeddedComment =+    parseEditorConfig "[*]\nshellcheck.disable=SC2148 #abc\n" "foo" == ""+-- EditorConfig does not allow inline comments, so a trailing '# ...'+-- makes the value invalid (the .shellcheckrc parser's+-- shellForExecutable lookup fails on the embedded text), and the+-- directive is dropped. It is reported via invalidDirectiveLines.+prop_parseEditorConfigInlineComment =+    parseEditorConfig "[*]\nshellcheck.shell=bash # inline\n" "foo" == ""+-- Full-line comments starting on first non-ws char are stripped.+prop_parseEditorConfigLineComment =+    parseEditorConfig "[*]\n# shellcheck.shell=bash\n" "foo" == ""+prop_parseEditorConfigSemicolonComment =+    parseEditorConfig "[*]\n; shellcheck.shell=bash\n" "foo" == ""+-- Empty brace alternative makes the glob group optional; 'foo' matches+-- '[foo{,bar}]'.+prop_parseEditorConfigBraceEmpty =+    parseEditorConfig "[foo{,bar}]\nshellcheck.shell=sh\n" "foo" == "\nshell=sh\n"+-- Nested braces are expanded correctly; 'baz' matches+-- '[{foo,ba{r,z}}]'.+prop_parseEditorConfigBraceNested =+    parseEditorConfig "[{foo,ba{r,z}}]\nshellcheck.shell=sh\n" "baz" == "\nshell=sh\n"+prop_isEditorConfigRootEmpty = not $ isEditorConfigRoot "root =\n"+prop_isEditorConfigRootFalse = not $ isEditorConfigRoot "root = false\n"+prop_isEditorConfigRootTrue = isEditorConfigRoot "root = TRUE\n"+prop_invalidRootLinesEmpty = invalidRootLines "root =\n" == [1]+prop_invalidRootLinesTrue = invalidRootLines "root = true\n" == []+prop_invalidRootLinesFalse = invalidRootLines "root = false\n" == []+prop_invalidRootLinesInSection =+    invalidRootLines "[*]\nroot = true\n" == []+-- An unsupported non-empty shell is reported at its line.+prop_invalidDirectiveLinesUnknownShell =+    invalidDirectiveLines "[*]\nshellcheck.shell=zsh\n" "foo" == [2]+-- An empty shell is valid (the rc parser rejects it), so no error.+prop_invalidDirectiveLinesEmptyShell =+    invalidDirectiveLines "[*]\nshellcheck.shell=\n" "foo" == []+-- A known shell is fine.+prop_invalidDirectiveLinesKnownShell =+    invalidDirectiveLines "[*]\nshellcheck.shell=bash\n" "foo" == []+-- A '#'-prefixed value is reported (EditorConfig has no inline comments).+prop_invalidDirectiveLinesHashValue =+    invalidDirectiveLines "[foo]\nshellcheck.disable = #abc\n" "foo" == [2]+-- A ';'-prefixed value is reported too.+prop_invalidDirectiveLinesSemicolonValue =+    invalidDirectiveLines "[foo]\nshellcheck.disable = ;abc\n" "foo" == [2]+-- A '#' embedded anywhere in the value (not just at the start) is+-- reported too: previously this was silently accepted, since the+-- .shellcheckrc parser would treat everything from the '#' onwards as a+-- trailing comment (e.g. this used to disable SC2148 without warning).+prop_invalidDirectiveLinesEmbeddedHashValue =+    invalidDirectiveLines "[foo]\nshellcheck.disable = SC2148 #abc\n" "foo" == [2]+prop_invalidDirectiveLinesEmbeddedSemicolonValue =+    invalidDirectiveLines "[foo]\nshellcheck.disable = SC2148 ;abc\n" "foo" == [2]+-- A plain empty value (no comment marker) is not reported: it is simply+-- a no-op, unlike a value that was truncated down to empty by a leading+-- comment marker.+prop_invalidDirectiveLinesEmptyValueNotInvalid =+    invalidDirectiveLines "[foo]\nshellcheck.disable =\n" "foo" == []+-- A plain invalid value (no comment marker) is not reported here; it is+-- rejected by the .shellcheckrc parser as SC1134 instead.+prop_invalidDirectiveLinesPlainValue =+    invalidDirectiveLines "[foo]\nshellcheck.disable = abc\n" "foo" == []+-- Directives in non-matching sections are ignored.+prop_invalidDirectiveLinesNoMatch =+    invalidDirectiveLines "[*.txt]\nshellcheck.shell=zsh\n" "foo" == []+-- Only the matching section's invalid directive is reported.+prop_invalidDirectiveLinesMatchingSection =+    invalidDirectiveLines "[*.txt]\nshellcheck.shell=zsh\n[foo]\nshellcheck.shell=bash\n" "foo" == []++return []+runTests = $quickCheckAll
src/ShellCheck/Formatter/Diff.hs view
@@ -191,11 +191,17 @@     let (last, rest) = splitAt 1 $ reverse x     in (reverse rest, last) +-- git patch does not like `\` on Windows+normalizePath path =+    case path of+        c:rest -> (if c == pathSeparator then '/' else c) : normalizePath rest+        [] -> []+ formatDoc color (DiffDoc name lf regions) =     let (most, last) = splitLast regions     in-          (color bold $ "--- " ++ ("a" </> name)) ++ "\n" ++-          (color bold $ "+++ " ++ ("b" </> name)) ++ "\n" +++          (color bold $ "--- " ++ (normalizePath $ "a" </> name)) ++ "\n" +++          (color bold $ "+++ " ++ (normalizePath $ "b" </> name)) ++ "\n" ++           concatMap (formatRegion color LinefeedOk) most ++           concatMap (formatRegion color lf) last 
src/ShellCheck/Formatter/JSON1.hs view
@@ -120,7 +120,7 @@         let filename = sourceFile (NE.head group)         result <- siReadFile sys (Just True) filename         let contents = either (const "") id result-        let comments' = makeNonVirtual comments contents+        let comments' = makeNonVirtual (NE.toList group) contents         deepseq comments' $ modifyIORef ref (\x -> comments' ++ x)  finish ref = do
src/ShellCheck/Formatter/TTY.hs view
@@ -17,7 +17,7 @@     You should have received a copy of the GNU General Public License     along with this program.  If not, see <https://www.gnu.org/licenses/>. -}-module ShellCheck.Formatter.TTY (format) where+module ShellCheck.Formatter.TTY (format, wikiLink) where  import ShellCheck.Fixer import ShellCheck.Interface@@ -169,7 +169,7 @@             -- and/or other unrelated lines.             let (excerptFix, excerpt) = sliceFile mergedFix fileLines             -- in the spirit of error prone-            putStrLn $ color "message" "Did you mean: "+            putStrLn $ color "message" "Did you mean:"             putStrLn $ unlines $ applyFix excerptFix excerpt  cuteIndent :: PositionedComment -> String
src/ShellCheck/Interface.hs view
@@ -37,6 +37,7 @@     , Comment(cSeverity, cCode, cMessage)     , PositionedComment(pcStartPos , pcEndPos , pcComment, pcFix)     , ColorOption(ColorAuto, ColorAlways, ColorNever)+    , ExtendedAnalysisMode(ExtendedAnalysisNone, ExtendedAnalysisLocal, ExtendedAnalysisFull)     , TokenComment(tcId, tcComment, tcFix)     , emptyCheckResult     , newAnalysisResult@@ -57,7 +58,7 @@     , InsertionPoint(InsertBefore, InsertAfter)     , Replacement(repStartPos, repEndPos, repString, repPrecedence, repInsertionPoint)     , newReplacement-    , CheckDescription(cdName, cdDescription, cdPositive, cdNegative)+    , CheckDescription(cdName, cdId, cdDescription, cdPositive, cdNegative)     , newCheckDescription     ) where @@ -100,7 +101,7 @@     csIncludedWarnings :: Maybe [Integer],     csShellTypeOverride :: Maybe Shell,     csMinSeverity :: Severity,-    csExtendedAnalysis :: Maybe Bool,+    csExtendedAnalysis :: Maybe ExtendedAnalysisMode,     csOptionalChecks :: [String] } deriving (Show, Eq) @@ -176,7 +177,7 @@     asExecutionMode :: ExecutionMode,     asCheckSourced :: Bool,     asOptionalChecks :: [String],-    asExtendedAnalysis :: Maybe Bool,+    asExtendedAnalysis :: Maybe ExtendedAnalysisMode,     asTokenPositions :: Map.Map Id (Position, Position) } @@ -212,6 +213,7 @@  data CheckDescription = CheckDescription {     cdName :: String,+    cdId :: [Integer],     cdDescription :: String,     cdPositive :: String,     cdNegative :: String@@ -219,6 +221,7 @@  newCheckDescription = CheckDescription {     cdName = "",+    cdId = [],     cdDescription = "",     cdPositive = "",     cdNegative = ""@@ -321,6 +324,13 @@     | ColorAlways     | ColorNever   deriving (Ord, Eq, Show)++-- The scope of the data-flow ("extended") analysis+data ExtendedAnalysisMode =+    ExtendedAnalysisNone      -- No data-flow analysis.+    | ExtendedAnalysisLocal   -- Dataflow analysis stops at 'source' boundaries+    | ExtendedAnalysisFull    -- Whole-program: data flow is followed into sourced files.+    deriving (Ord, Eq, Show)  -- For testing mockedSystemInterface :: [(String, String)] -> SystemInterface Identity
src/ShellCheck/Parser.hs view
@@ -21,6 +21,7 @@ {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE NondecreasingIndentation #-} module ShellCheck.Parser (parseScript, runTests) where  import ShellCheck.AST@@ -48,6 +49,7 @@ import qualified Control.Monad.State as Ms import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as Map+import Debug.Trace  import Test.QuickCheck.All (quickCheckAll) @@ -66,10 +68,14 @@ doubleQuote = char '"' variableStart = upper <|> lower <|> oneOf "_" variableChars = upper <|> lower <|> digit <|> oneOf "_"--- Chars to allow in function names-functionChars = variableChars <|> oneOf ":+?-./^@,"+-- Chars to allow function names to start with+functionStartChars = variableChars <|> oneOf ":+?-./^@,"+-- Chars to allow inside function names+functionChars = variableChars <|> oneOf "#:+?-./^@,"+-- Chars to allow function names to start with, using the 'function' keyword+extendedFunctionStartChars = functionStartChars <|> oneOf "[]*=!" -- Chars to allow in functions using the 'function' keyword-extendedFunctionChars = functionChars <|> oneOf "[]*=!"+extendedFunctionChars = extendedFunctionStartChars <|> oneOf "[]*=!" specialVariable = oneOf (concat specialVariables) paramSubSpecialChars = oneOf "/:+-=%" quotableChars = "|&;<>()\\ '\t\n\r\xA0" ++ doubleQuotableChars@@ -141,15 +147,9 @@     parseProblemAt pos ErrorC 1017 "Literal carriage return. Run script through tr -d '\\r' ."     return '\r' -almostSpace =-    choice [-        check '\xA0' "unicode non-breaking space",-        check '\x200B' "unicode zerowidth space"-    ]-  where-    check c name = do-        parseNote ErrorC 1018 $ "This is a " ++ name ++ ". Delete and retype it."-        char c+almostSpace = do+        parseNote ErrorC 1018 $ "This is a unicode space. Delete and retype it."+        oneOf "\xA0\x2002\x2003\x2004\x2005\x2006\x2007\x2008\x2009\x200B\x202F"         return ' '  --------- Message/position annotation on top of user state@@ -169,14 +169,16 @@     positionMap :: Map.Map Id (SourcePos, SourcePos),     parseNotes :: [ParseNote],     hereDocMap :: Map.Map Id [Token],-    pendingHereDocs :: [HereDocContext]+    pendingHereDocs :: [HereDocContext],+    parseShellType :: Shell } initialUserState = UserState {     lastId = Id $ -1,     positionMap = Map.empty,     parseNotes = [],     hereDocMap = Map.empty,-    pendingHereDocs = []+    pendingHereDocs = [],+    parseShellType = Bash }  codeForParseNote (ParseNote _ _ _ code _) = code@@ -695,8 +697,13 @@         return term      readCondNot = do+        notFollowedBy2 $ do+            readEscaped $ string "!"+            spacingOrLf+            choice $ map (try . string) binaryTestOps+         start <- startSpan-        char '!'+        if single then void (try (readRegularOrEscaped (string "!"))) else void (char '!')         id <- endSpan start         spacingOrLf         expr <- readCondExpr@@ -827,7 +834,7 @@         char ')'         id <- endSpan start         spacing-        return $ TA_Parentesis id s+        return $ TA_Parenthesis id s      readArithTerm = readGroup <|> readVariable <|> readExpansion @@ -947,6 +954,14 @@ prop_readCondition27 = not $ isOk readConditionCommand "[[ x ]] foo" prop_readCondition28 = isOk readCondition "[[ x = [\"$1\"] ]]" prop_readCondition29 = isOk readCondition "[[ x = [*] ]]"+prop_readCondition30 = isOk readCondition "[ \\! \\( -e foo -a -e bar \\) ]"+prop_readCondition31 = isOk readCondition "[ '!' = $x ]"+prop_readCondition32 = isOk readCondition "[ \"!\" = $x ]"+prop_readCondition33 = isOk readCondition "[ \\! = $x ]"+prop_readCondition34 = isWarning readCondition "[ !x = $x ]"+prop_readCondition35 = isWarning readCondition "[ \\!x = $x ]"+prop_readCondition36 = isWarning readCondition "[ '!'x = $x ]"+prop_readCondition37 = isOk readCondition "[ '!' x = $x ]"  readCondition = called "test expression" $ do     opos <- getPosition@@ -977,7 +992,8 @@     when (open == "[[" && close /= "]]") $ parseProblemAt cpos ErrorC 1033 "Test expression was opened with double [[ but closed with single ]. Make sure they match."     when (open == "[" && close /= "]" ) $ parseProblemAt opos ErrorC 1034 "Test expression was opened with single [ but closed with double ]]. Make sure they match."     spacing-    return $ T_Condition id typ condition+    let closeTyp = if close == "]" then SingleBracket else DoubleBracket+    return $ T_Condition id typ closeTyp condition  readAnnotationPrefix = do     char '#'@@ -995,6 +1011,21 @@ prop_readAnnotation9 = isOk readAnnotation "# shellcheck source='foo bar' source-path=\"baz etc\"\n" prop_readAnnotation10 = isOk readAnnotation "# shellcheck disable='SC1234,SC2345' enable=\"foo\" shell='bash'\n" prop_readAnnotation11 = isOk (readAnnotationWithoutPrefix False) "external-sources='true'"+prop_readAnnotation12 = isOk readAnnotation "# shellcheck disable=2034-2036\n"+prop_readAnnotation13 = isOk readAnnotation "# shellcheck disable=all,SC2034\n"+prop_readAnnotation14 = isNotOk readAnnotation "# shellcheck disable=foo\n"+prop_readAnnotation15 = isNotOk readAnnotation "# shellcheck disable='foo'\n"+prop_readAnnotation16 = isNotOk readAnnotation "# shellcheck disable=SC2034-x\n"+-- #3425: an invalid disable value should blame the value, not a missing '='+prop_readAnnotationBadDisableMessage =+    "Unknown disable value 'foo'" `isInfixOf` rendered+        && not ("Expected '=' after directive key" `isInfixOf` rendered)+  where+    rendered = case res of+        Left err -> getStringFromParsec $ errorMessages err+        Right _ -> ""+    (res, _) = runIdentity $+        runParser testEnvironment readAnnotation "-" "# shellcheck disable=foo\n"  readAnnotation = called "shellcheck directive" $ do     try readAnnotationPrefix@@ -1023,7 +1054,19 @@         key <- many1 (letter <|> char '-')         char '=' <|> fail "Expected '=' after directive key"         annotations <- case key of-            "disable" -> plainOrQuoted $ readElement `sepBy` char ','+            "disable" -> do+                pos <- getPosition+                str <- quoted (many1 anyChar)+                    <|> many1 (letter <|> digit <|> char '-' <|> char ',')+                    <|> return ""+                parsed <- subParse pos+                    (try (Just <$> (readElement `sepBy` char ',' <* eof))+                        <|> return Nothing)+                    str+                case parsed of+                    Just annotations -> return annotations+                    Nothing -> fail ("Unknown disable value '" ++ str+                        ++ "'. Expected a code like 'SC2000', or a range like 'SC2000-SC3000', or 'all'.")               where                 readElement = readRange <|> readAll                 readAll = do@@ -1062,10 +1105,13 @@                 pos <- getPosition                 value <- plainOrQuoted $ many1 letter                 case value of-                    "true" -> return [ExtendedAnalysis True]-                    "false" -> return [ExtendedAnalysis False]+                    "true" -> return [ExtendedAnalysis EAAFull]+                    "false" -> return [ExtendedAnalysis EAANone]+                    "full" -> return [ExtendedAnalysis EAAFull]+                    "local" -> return [ExtendedAnalysis EAALocal]+                    "none" -> return [ExtendedAnalysis EAANone]                     _ -> do-                        parseNoteAt pos ErrorC 1146 "Unknown extended-analysis value. Expected true/false."+                        parseNoteAt pos ErrorC 1146 "Unknown extended-analysis value. Expected full/local/none (or true/false)."                         return []              "external-sources" -> do@@ -1701,16 +1747,17 @@  prop_readDollarBraceCommandExpansion1 = isOk readDollarBraceCommandExpansion "${ ls; }" prop_readDollarBraceCommandExpansion2 = isOk readDollarBraceCommandExpansion "${\nls\n}"-readDollarBraceCommandExpansion = called "ksh ${ ..; } command expansion" $ do+prop_readDollarBraceCommandExpansion3 = isOk readDollarBraceCommandExpansion "${|  REPLY=42; }"+readDollarBraceCommandExpansion = called "ksh-style ${ ..; } command expansion" $ do     start <- startSpan-    try $ do-        string "${"-        whitespace+    c <- try $ do+            string "${"+            char '|' <|> whitespace     allspacing     term <- readTerm-    char '}' <|> fail "Expected } to end the ksh ${ ..; } command expansion"+    char '}' <|> fail "Expected } to end the ksh-style ${ ..; } command expansion"     id <- endSpan start-    return $ T_DollarBraceCommandExpansion id term+    return $ T_DollarBraceCommandExpansion id (if c == '|' then Piped else Unpiped) term  prop_readDollarBraced1 = isOk readDollarBraced "${foo//bar/baz}" prop_readDollarBraced2 = isOk readDollarBraced "${foo/'{cow}'}"@@ -2060,6 +2107,8 @@                     "Unexpected start of line. If breaking lines, |/||/&& should be at the end of the previous one." readLineBreak = optional readNewlineList +data BackgroundOperator = Ampersand | Coprocess+ prop_readSeparator1 = isWarning readScript "a &; b" prop_readSeparator2 = isOk readScript "a & b" prop_readSeparator3 = isWarning readScript "a &amp; b"@@ -2069,7 +2118,7 @@     notFollowedBy2 (void g_AND_IF <|> void readCaseSeparator)     notFollowedBy2 (string "&>")     start <- getPosition-    f <- try (do+    f <- (Just Coprocess <$ readKshCoprocessOp) <|> try (do                     pos <- getPosition                     char '&'                     optional $ choice [@@ -2089,12 +2138,18 @@                     -- In case statements we might have foo & ;;                     notFollowedBy2 $ char ';'                     parseProblemAt pos ErrorC 1045 "It's not 'foo &; bar', just 'foo & bar'."-                    return '&'-            ) <|> char ';' <|> char '&'+                    return $ Just Ampersand+            ) <|> (Nothing <$ char ';') <|> (Just Ampersand <$ char '&')     end <- getPosition     spacing     return (f, (start, end)) +-- In Ksh, |& terminates the preceding and-or list, like &.+readKshCoprocessOp = do+    shell <- parseShellType <$> getState+    guard $ shell == Ksh+    void $ try $ string "|&"+ readSequentialSep = void (g_Semi >> readLineBreak) <|> void readNewlineList readSeparator =     do@@ -2106,7 +2161,7 @@             start <- getPosition             readNewlineList             end <- getPosition-            return ('\n', (start, end))+            return (Nothing, (start, end))  prop_readSimpleCommand = isOk readSimpleCommand "echo test > file" prop_readSimpleCommand2 = isOk readSimpleCommand "cmd &> file"@@ -2124,6 +2179,10 @@ prop_readSimpleCommand13 = isWarning readSimpleCommand "ElseIf foo" prop_readSimpleCommand14 = isWarning readSimpleCommand "elseif[$i==2]" prop_readSimpleCommand15 = isWarning readSimpleCommand "trap 'foo\"bar' INT"+prop_readSimpleCommand16 = isOk readSimpleCommand "builtin export foo=(bar baz)"+prop_readSimpleCommand17 = isOk readSimpleCommand "builtin declare -a foo=(bar baz)"+prop_readSimpleCommand18 = isNotOk readSimpleCommand "builtin echo foo=(bar baz)"+prop_readSimpleCommand19 = isNotOk readSimpleCommand "echo export foo=(bar baz)" readSimpleCommand = called "simple command" $ do     prefix <- option [] readCmdPrefix     skipAnnotationAndWarn@@ -2139,10 +2198,13 @@       Just cmd -> do             validateCommand cmd             -- We have to ignore possible parsing problems from the lookAhead parser-            firstArgument <- ignoreProblemsOf . optionMaybe . try . lookAhead $ readCmdWord+            -- Only look ahead after `builtin`: parsing every first argument twice doubles the work per nested $(..)+            firstArgument <- if isCommand ["builtin"] cmd+                then ignoreProblemsOf . optionMaybe . try . lookAhead $ readCmdWord+                else return Nothing             suffix <- option [] $ getParser readCmdSuffix                     -- If `export` or other modifier commands are called with `builtin` we have to look at the first argument-                    (if isCommand ["builtin"] cmd then fromMaybe cmd firstArgument else cmd) [+                    (fromMaybe cmd firstArgument) [                         (["declare", "export", "local", "readonly", "typeset"], readModifierSuffix),                         (["time"], readTimeSuffix),                         (["let"], readLetSuffix),@@ -2211,17 +2273,18 @@   readSource :: Monad m => Token -> SCParser m Token-readSource t@(T_Redirecting _ _ (T_SimpleCommand cmdId _ (cmd:file':rest'))) = do-    let file = getFile file' rest'+readSource t@(T_Redirecting _ _ (T_SimpleCommand cmdId _ (cmd:args'))) = do+    let file = getFile args'     override <- getSourceOverride     let literalFile = do-        name <- override `mplus` getLiteralString file `mplus` stripDynamicPrefix file+        name <- override `mplus` (getLiteralString =<< file) `mplus` (stripDynamicPrefix =<< file)         -- Hack to avoid 'source ~/foo' trying to read from literal tilde         guard . not $ "~/" `isPrefixOf` name         return name+    let fileId = fromMaybe (getId cmd) (getId <$> file)     case literalFile of         Nothing -> do-            parseNoteAtId (getId file) WarningC 1090+            parseNoteAtId fileId WarningC 1090                 "ShellCheck can't follow non-constant source. Use a directive to specify location."             return t         Just filename -> do@@ -2229,7 +2292,7 @@             if not proceed               then do                 -- FIXME: This actually gets squashed without -a-                parseNoteAtId (getId file) InfoC 1093+                parseNoteAtId fileId InfoC 1093                     "This file appears to be recursively sourced. Ignoring."                 return t               else do@@ -2247,7 +2310,7 @@                         return (contents, resolved)                 case input of                     Left err -> do-                        parseNoteAtId (getId file) InfoC 1091 $+                        parseNoteAtId fileId InfoC 1091 $                             "Not following: " ++ err                         return t                     Right script -> do@@ -2259,18 +2322,19 @@                             return $ T_SourceCommand id1 t (T_Include id2 src)                          let failed = do-                            parseNoteAtId (getId file) WarningC 1094+                            parseNoteAtId fileId WarningC 1094                                 "Parsing of sourced file failed. Ignoring it."                             return t                          included <|> failed   where-    getFile :: Token -> [Token] -> Token-    getFile file (next:rest) =-        case getLiteralString file of-            Just "--" -> next-            x -> file-    getFile file _ = file+    getFile :: [Token] -> Maybe Token+    getFile (first:rest) =+        case getLiteralString first of+            Just "--" -> rest !!! 0+            Just "-p" -> rest !!! 1+            _ -> return first+    getFile _ = Nothing      getSourcePath t =         case t of@@ -2351,6 +2415,14 @@         return []  prop_readTerm = isOk readTerm "time ( foo; bar; )"+prop_readKshCoprocessAndOr =+    case debugParse readScript "#!/bin/ksh\ntrue && echo data |& read -r -p record" of+        Right (T_Annotation _ _ (T_Script _ _ [T_KshCoprocess _ (T_AndIf _ _ _), _])) -> True+        _ -> False++prop_readKshCoprocessBeforeClosingDelimiter =+    isOk readScript "#!/bin/ksh\n{ true|& }"+ readTerm = do     allspacing     m <- readAndOr@@ -2368,8 +2440,9 @@           <|>             return [current]       where-        transformWithSeparator i '&' = T_Backgrounded i-        transformWithSeparator i _  = id+        transformWithSeparator i (Just Ampersand) = T_Backgrounded i+        transformWithSeparator i (Just Coprocess) = T_KshCoprocess i+        transformWithSeparator _ Nothing = id   readPipeSequence = do@@ -2389,6 +2462,7 @@  readPipe = do     notFollowedBy2 g_OR_IF+    notFollowedBy2 readKshCoprocessOp     start <- startSpan     char '|'     qualifier <- string "&" <|> return ""@@ -2757,6 +2831,8 @@ prop_readFunctionDefinition11 = isWarning readFunctionDefinition "function foo{\ntrue\n}" prop_readFunctionDefinition12 = isOk readFunctionDefinition "function []!() { true; }" prop_readFunctionDefinition13 = isOk readFunctionDefinition "@require(){ true; }"+prop_readFunctionDefinition14 = isOk readFunctionDefinition "foo#bar(){ :; }"+prop_readFunctionDefinition15 = isNotOk readFunctionDefinition "#bar(){ :; }" readFunctionDefinition = called "function" $ do     start <- startSpan     functionSignature <- try readFunctionSignature@@ -2774,7 +2850,7 @@                 string "function"                 whitespace             spacing-            name <- many1 extendedFunctionChars+            name <- (:) <$> extendedFunctionStartChars <*> many extendedFunctionChars             spaces <- spacing             hasParens <- wasIncluded readParens             when (not hasParens && null spaces) $@@ -2783,7 +2859,7 @@             return $ \id -> T_Function id (FunctionKeyword True) (FunctionParentheses hasParens) name          readWithoutFunction = try $ do-            name <- many1 functionChars+            name <- (:) <$> functionStartChars <*> many functionChars             guard $ name /= "time"  -- Interferes with time ( foo )             spacing             readParens@@ -2801,17 +2877,29 @@ prop_readCoProc1 = isOk readCoProc "coproc foo { echo bar; }" prop_readCoProc2 = isOk readCoProc "coproc { echo bar; }" prop_readCoProc3 = isOk readCoProc "coproc echo bar"+prop_readCoProc4 = isOk readCoProc "coproc a=b echo bar"+prop_readCoProc5 = isOk readCoProc "coproc 'foo' { echo bar; }"+prop_readCoProc6 = isOk readCoProc "coproc \"foo$$\" { echo bar; }"+prop_readCoProc7 = isOk readCoProc "coproc 'foo' ( echo bar )"+prop_readCoProc8 = isOk readCoProc "coproc \"foo$$\" while true; do true; done" readCoProc = called "coproc" $ do     start <- startSpan     try $ do         string "coproc"-        whitespace+        spacing1     choice [ try $ readCompoundCoProc start, readSimpleCoProc start ]   where     readCompoundCoProc start = do-        var <- optionMaybe $-            readVariableName `thenSkip` whitespace-        body <- readBody readCompoundCommand+        notFollowedBy2 readAssignmentWord+        (var, body) <- choice [+            try $ do+                body <- readBody readCompoundCommand+                return (Nothing, body),+            try $ do+                var <- readNormalWord `thenSkip` spacing+                body <- readBody readCompoundCommand+                return (Just var, body)+            ]         id <- endSpan start         return $ T_CoProc id var body     readSimpleCoProc start = do@@ -3176,9 +3264,14 @@ prop_readShebang5 = isWarning readShebang "\n#!/bin/sh" prop_readShebang6 = isWarning readShebang " # Copyright \n!#/bin/bash" prop_readShebang7 = isNotOk readShebang "# Copyright \nfoo\n#!/bin/bash"+prop_readShebang8 = isWarning readShebang "#  !/bin/bash\n"+prop_readShebang9 = isNotOk readShebang "#  !   Grave\n"+prop_readShebang10 = isWarning readShebang "# Copyright\n# ! /bin/bash\n"+prop_readShebang11 = isNotOk readShebang "# Some of the accent codes:\n#  !   Grave\n"+prop_readShebang12 = isWarning readShebang "# Some of the accent codes:\n#  !   Grave\n#!/bin/bash\n" readShebang = do     start <- startSpan-    anyShebang <|> try readMissingBang <|> withHeader+    anyShebang <|> try readMissingBang <|> try withHeader     many linewhitespace     str <- many $ noneOf "\r\n"     id <- endSpan start@@ -3209,6 +3302,8 @@         middlePos <- getPosition         middleSpaces <- skipSpaces         char '!'+        -- Don't consider a comment like "#  ! Note" a shebang unless a path follows+        when middleSpaces $ void ensurePathAhead         when startSpaces $             parseProblemAt startPos ErrorC 1114                 "Remove leading spaces before the shebang."@@ -3229,6 +3324,8 @@         ensurePathAhead         parseProblemAt pos ErrorC 1113             "Use #!, not just #, for the shebang."+        -- Emit a warning, but don't consider a leading comment a valid shebang+        fail ""      ensurePathAhead = lookAhead $ do         many linewhitespace@@ -3274,13 +3371,18 @@             Just (file, str) -> readConfig file str      readConfig filename contents = do-        result <- lift $ runParserT readConfigKVs initialUserState filename contents+        result <- lift $+            runParserT (parseWithNotes readConfigKVs) initialUserState filename contents         case result of-            Right result ->-                return result+            Right (annotations, userState) -> do+                mapM_ addParseNote (parseNotes userState)+                return annotations              Left err -> do-                parseProblem ErrorC 1134 $ errorFor filename err+                -- Report the error at its location in the config file+                -- (e.g. .shellcheckrc or .editorconfig), not at the+                -- current position in the script being checked.+                parseProblemAt (errorPos err) ErrorC 1134 $ errorFor filename err                 return []      errorFor filename err =@@ -3337,13 +3439,19 @@             annotationId <- endSpan annotationStart             let shellAnnotationSpecified =                     any (\x -> case x of ShellOverride {} -> True; _ -> False) annotations-            shellFlagSpecified <- isJust <$> Mr.asks shellTypeOverride-            let ignoreShebang = shellAnnotationSpecified || shellFlagSpecified+            shellOverride <- Mr.asks shellTypeOverride+            let ignoreShebang = shellAnnotationSpecified || isJust shellOverride+            let executable = executableFromShebang shebangString              unless ignoreShebang $-                verifyShebang pos (executableFromShebang shebangString)-            if ignoreShebang || isValidShell (executableFromShebang shebangString) /= Just False+                verifyShebang pos executable+            if ignoreShebang || isValidShell executable /= Just False               then do+                    unless sourced $ do+                        filename <- Mr.asks currentFilename+                        let dialect = fromMaybe Bash $ msum+                                [shellOverride, shellFromAnnotations annotations executable, shellFromFilename filename]+                        modifyState $ \state -> state { parseShellType = dialect }                     commands <- readCompoundListOrEmpty                     id <- endSpan start                     readPendingHereDocs@@ -3381,7 +3489,8 @@         "busybox sh",         "bash",         "bats",-        "ksh"+        "ksh",+        "oksh"         ]     badShells = [         "awk",@@ -3390,6 +3499,7 @@         "fish",         "perl",         "python",+        "python3",         "ruby",         "tcsh",         "zsh"@@ -3442,14 +3552,23 @@ isWarning p s = parsesCleanly p s == Just False  -- The string parses with warnings isNotOk p s =   parsesCleanly p s == Nothing     -- The string does not parse -parsesCleanly parser string = runIdentity $ do-    (res, sys) <- runParser testEnvironment-                    (parser >> eof >> getState) "-" string-    case (res, sys) of-        (Right userState, systemState) ->-            return $ Just . null $ parseNotes userState ++ parseProblems systemState-        (Left _, _) -> return Nothing+-- If the parser matches the string, return Right [ParseNotes+ParseProblems]+-- If it does not match the string,  return Left  [ParseProblems]+getParseOutput parser string = runIdentity $ do+    (res, systemState) <- runParser testEnvironment+                            (parser >> eof >> getState) "-" string+    return $ case res of+        Right userState ->+            Right $ parseNotes userState ++ parseProblems systemState+        Left _ -> Left $ parseProblems systemState +-- If the parser matches the string, return Just whether it was clean (without emitting suggestions)+-- Otherwise, Nothing+parsesCleanly parser string =+    case getParseOutput parser string of+        Right list -> Just $ null list+        Left _ -> Nothing+ parseWithNotes parser = do     item <- parser     state <- getState@@ -3494,9 +3613,10 @@ parseShell env name contents = do     (result, state) <- runParser env (parseWithNotes readScript) name contents     case result of-        Right (script, userstate) ->+        Right (script, userstate) -> do+            let isScriptLevelDisabled c = isAnnotationIgnoringCode (codeForParseNote c) script             return newParseResult {-                prComments = map toPositionedComment $ nub $ parseNotes userstate ++ parseProblems state,+                prComments = map toPositionedComment $ filter (not . isScriptLevelDisabled) $ nub $ parseNotes userstate ++ parseProblems state,                 prTokenPositions = Map.map startEndPosToPos (positionMap userstate),                 prRoot = Just script             }
striptests view
@@ -40,7 +40,7 @@     # Delete tests     /^prop_/ { state = 1; next; } -    # ..and any blank lines following them.+    # ..and any indented lines following them.     state == 1 && /^ / { next; }      # Template Haskell marker@@ -60,7 +60,7 @@   exit 1 fi -if [[ -d '.git' ]] && ! git diff --exit-code > /dev/null 2>&1+if [[ -d '.git' ]] && git --version > /dev/null && ! git diff --exit-code > /dev/null 2>&1 then   echo "You have local changes! These may be overwritten." >&2   exit 2
test/shellcheck.hs view
@@ -12,6 +12,7 @@ import qualified ShellCheck.Checks.ControlFlow import qualified ShellCheck.Checks.Custom import qualified ShellCheck.Checks.ShellSupport+import qualified ShellCheck.EditorConfig import qualified ShellCheck.Fixer import qualified ShellCheck.Formatter.Diff import qualified ShellCheck.Parser@@ -35,6 +36,7 @@       , ("Checks.ControlFlow" , ShellCheck.Checks.ControlFlow.runTests)       , ("Checks.Custom"      , ShellCheck.Checks.Custom.runTests)       , ("Checks.ShellSupport", ShellCheck.Checks.ShellSupport.runTests)+      , ("EditorConfig"       , ShellCheck.EditorConfig.runTests)       , ("Fixer"              , ShellCheck.Fixer.runTests)       , ("Formatter.Diff"     , ShellCheck.Formatter.Diff.runTests)       , ("Parser"             , ShellCheck.Parser.runTests)