Skip to content

Constant sprintf() calls #2183

Open
Open

Description

@Bisaloo

I see the following unnecessary sprintf() across the codebase I maintain:

sprintf("hello")

sprintf("%s", "hello")

In other words:

  • sprintf() does not have any arguments passed to ...
  • sprintf() fmt is "%s" and the next argument in a STR_CONST.

These two examples could be replaced by a more readable and more efficient "hello".

I believe the existing sprintf_linter() infrastructure and in particular the logic around piped calls could be re-used here. If you believe this would be a good improvement, I can give it a try.

Activity

  1. MichaelChirico commented on Sep 18, 2023

    @MichaelChirico
    Collaborator

    only question is if it maybe belongs under literal_coercion_linter(). I also see paste("...") cases that should lint similarly, so maybe sprintf_linter() is too specific.

  2. AshesITR commented on Sep 18, 2023

    @AshesITR
    Collaborator

    I think sprintf_linter() is a good place (and paste_linter() for the other case). There is no coercion going on in sprintf("%s", "a").

  3. added
    feature
    on Sep 18, 2023
  4. added a commit that references this issue on Sep 18, 2023
  5. MichaelChirico commented on Feb 18, 2025

    @MichaelChirico
    Collaborator

    There's some subtlety here, it's not quite trivial to implement:

    sprintf("%s")         # already lints b/c '%s' is not matched
    sprintf("abc")        # needs to lint because there's no template at all
    sprintf("def", "ghi") # already lints b/c 'ghi' doesn't correspond to anything

    i.e. it's not as simple as "find sprintf() calls with just one argument", it's got to first subset among those calls that don't already generate a lint.

    Not particularly difficult, but requires a bit more care.

  6. AshesITR commented on Feb 22, 2025

    @AshesITR
    Collaborator

    Another edge case to be aware of is sprintf("%%") and sprintf("%%", ""). The former could lint (replace by "%"). The latter already lints.

    contains(text(), '%') is too simple.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions