Skip to content

Object name linter performance improvements - #236

Merged
russHyde merged 11 commits into
masterfrom
name_performance
Aug 23, 2019
Merged

russHyde merged 11 commits into
masterfrom
name_performance

Conversation

@jimhester

Copy link
Copy Markdown
Member

Fixes #226

jimhester and others added 8 commits April 10, 2017 13:05
Is both more robust and an order of magnitude more performant

    microbenchmark(
      {lint("R/lint.R", object_name_linter("snake_case"))},
      {lint("R/lint.R", object_name_linter_old("snake_case"))})
    #> Unit: milliseconds
    #>                                                         expr       min        lq      mean    median        uq      max neval
    #>  {     lint("R/lint.R", object_name_linter2("snake_case")) }  225.9701  252.2269  265.9434  263.2129  273.7824  483.367   100
    #>   {     lint("R/lint.R", object_name_linter("snake_case")) } 1275.5349 1360.3626 1430.6543 1425.3408 1486.9745 1735.298   100
In namespace_import, use package root by default instead of current directory
@codecov-io

codecov-io commented May 12, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #236 into master will decrease coverage by 0.61%.
The diff coverage is 88.73%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #236      +/-   ##
==========================================
- Coverage   85.65%   85.03%   -0.62%     
==========================================
  Files          39       41       +2     
  Lines        2140     2299     +159     
==========================================
+ Hits         1833     1955     +122     
- Misses        307      344      +37
Impacted Files Coverage Δ
R/zzz.R 0% <ø> (ø) ⬆️
R/deprecated.R 100% <ø> (ø) ⬆️
R/utils.R 74.48% <100%> (+0.26%) ⬆️
R/object_name_linters.R 79.83% <100%> (-20.17%) ⬇️
R/declared_functions.R 53.33% <53.33%> (ø)
R/namespace.R 92.3% <92.3%> (ø)
R/methods.R 35.64% <0%> (-1.86%) ⬇️
R/spaces_inside_linter.R 100% <0%> (ø) ⬆️
R/no_tab_linter.R 100% <0%> (ø) ⬆️
... and 4 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 65b312f...12c5a3a. Read the comment docs.

@fangly

fangly commented May 12, 2017

Copy link
Copy Markdown
Contributor

After your last commits, I now seem to get the expected results (expected for user-defined generics).

I can also confirm the speed improvement on my side with the latest commit:

#> Unit: milliseconds
#>                                                   expr       min        lq      mean    median        uq       max neval
#>     lint("R/lint.R", object_name_linter("snake_case"))  274.3952  299.7304  327.7372  309.7782  328.7454  878.4799   100
#> lint("R/lint.R", object_name_linter_old("snake_case")) 1898.8602 1964.9637 2071.5513 2039.2095 2105.9668 2789.1186   100

The only thing that I noticed is not quite right is that object_name_linter() is trying to match all the given styles instead of matching only one of them.

expect_lint("a_variable <- 1", NULL, linters = object_name_linter(styles = c("UPPERCASE", "snake_case")))
#> Error: got 1 lints instead of 0
#> list(filename = "C:\\Users\\u0000234\\AppData\\Local\\Temp\\Rtmp4AF5D3\\file5db282376e", line_number = 1, column_number = 1, type = "style", message = "Variable and function names should be in UPPERCASE.", line = "a_variable <- 1", ranges = list(c(1, 10)), linter = "object_name_linter")

@russHyde

Copy link
Copy Markdown
Collaborator

@jimhester would it be possible to rebase this change onto master and rerun the Travis runs?

@codecov

codecov Bot commented Aug 19, 2019 •

Copy link
Copy Markdown

Codecov Report

Merging #236 into master will decrease coverage by 0.62%.
The diff coverage is 89.28%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #236      +/-   ##
==========================================
- Coverage   82.37%   81.74%   -0.63%     
==========================================
  Files          42       44       +2     
  Lines        1889     1972      +83     
==========================================
+ Hits         1556     1612      +56     
- Misses        333      360      +27
Impacted Files Coverage Δ
R/zzz.R 0% <ø> (ø) ⬆️
R/utils.R 72.28% <100%> (+0.33%) ⬆️
R/declared_functions.R 53.33% <53.33%> (ø)
R/namespace.R 91.66% <91.66%> (ø)
R/object_name_linters.R 84.92% <98.21%> (-15.08%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 63d1cce...ee42404. Read the comment docs.

Comment thread R/object_name_linters.R Resolved
Comment thread R/object_name_linters.R Outdated
generics <- c(declared_s3_generics(x), namespace_imports()$fun, names(.knownS3Generics), .S3PrimitiveGenerics, ls(baseenv()))

lapply(styles, function(style) {
lapply(assignments[!check_style(nms, style, generics)], object_lint2, source_file, paste0("Variable and function names should be in ", style, "."), "object_name_linter")

@russHyde russHyde Aug 19, 2019 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 'assigned-names' that throw lints here, are those that do not match every one of the styles.
There is a test 'linter accepts a vector of styles' that has a different logic though. It expects lints to be thrown when an assigned-name does not match any of the styles.

Could the code logic be reworked to match the test, since it seems unworkable to expect every assigned name to match every one of a set of multiple styles.

@russHyde russHyde Aug 20, 2019 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For example,

lint_msg <- paste0(
  "Variable and function name style should be one of {",
  paste0(styles, collapse = ", "),
  "}."
)
style_matches <- lapply(styles, function(x) {
  check_style(nms, x, generics)
})
matches_a_style <- Reduce(`|`, style_matches)
lapply(
  assignments[!matches_a_style],
  object_lint2,
  source_file,
  lint_msg,
  "object_name_linter"
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the lint message is changed to reflect that multiple styles are checked, the expected lint message should be changed in a few tests

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A modified version of object_name_linter that Ive been using locally follows:

#' @describeIn linters  Check that object names conform to one of a set of
#'   naming styles.
#' @param styles A subset of
#'   \Sexpr[stage=render, results=rd]{lintr:::regexes_rd}.
#' @export
object_name_linter <- function(styles = "snake_case") {

  .or_string <- function(xs) {
    # returns "<S> or <T>"
    # where <T> is the last string in xs
    # where <S> is a comma-separated string of all entries in xs except <T>
    len <- length(xs)
    if (len <= 1) {
      return(xs)
    }
    comma_sepd_prefix <- paste(xs[-len], collapse = ", ")
    paste(comma_sepd_prefix, "or", xs[len])
  }

  styles <- match.arg(styles, names(style_regexes), several.ok = TRUE)

  lint_msg <- paste0(
    "Variable and function name style should be ", .or_string(styles), "."
  )

  function (source_file) {
    x <- global_xml_parsed_content(source_file)
    if (is.null(x)) {
      return()
    }
    xpath <- paste0(
      # Left hand assignments
      "//expr[SYMBOL or STR_CONST][following-sibling::LEFT_ASSIGN or following-sibling::EQ_ASSIGN]/*",

      # Or
      " | ",

      # Right hand assignments
      "//expr[SYMBOL or STR_CONST][preceding-sibling::RIGHT_ASSIGN]/*")

    assignments <- xml2::xml_find_all(x, xpath)

    # Retrieve assigned name
    nms <- strip_names(
      as.character(xml2::xml_find_first(assignments, "./text()")))

    generics <- c(
      declared_s3_generics(x),
      namespace_imports()$fun,
      names(.knownS3Generics),
      .S3PrimitiveGenerics, ls(baseenv()))

    style_matches <- lapply(styles, function(x) {
      check_style(nms, x, generics)
    })

    matches_a_style <- Reduce(`|`, style_matches)

    lapply(
      assignments[!matches_a_style],
      object_lint2,
      source_file,
      lint_msg,
      "object_name_linter"
    )
  }
}

@russHyde russHyde Aug 21, 2019 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this to match with the existing unit tests, I modified the expected lint-messages in tests "linter returns correct linting" and "linter accepts vector of styles" (and the style-name / argument-name in the latter):

  # "linter returns correct linting
  msg <- "Variable and function name style should be camelCase."
  # "linter accepts vector of styles"
  msg <- "Variable and function name style should be camelCase or dotted.case."
  linter <- object_name_linter(styles=c("camelCase", "dotted.case"))

@russHyde russHyde left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think most of the stuff I've pointed out will just help get the existing tests to pass (or modify the existing tests to match the new argument names and possible lint-message changes)

The PR seemed to relate to speeding up the object-name linter, so it would be good to see that the changes make a difference re speed on a decent sized file.

@russHyde

russHyde commented Aug 21, 2019 •

Copy link
Copy Markdown
Collaborator

Hi @jimhester

I've done a bit of exploration with this branch. All the points I mentioned in the code review are easily fixed (and I've addressed these in a branch locally; happy to append them on to this branch if that's technically possible).

There is a problem with formal arguments though.

This test fails:

  msg <- "Variable and function name style should be camelCase."                                                              
  linter <- object_name_linter("camelCase")
   ...
  expect_lint(                                                                                                                
    "Z = sapply('function', function(x=function(x){1}, b.a.z=F){identity(b.a.z)}, USE.NAMES=TRUE)",                           
    list(                                                                                                                     
      list(message=msg, line_number=1L, column_number=1L),                                                                    
      list(message=msg, line_number=1L, column_number=51L)                                                                    
    ),                                                                                                                        
    linter                                                                                                                    
  ) 

I tried debugging this test. During the object_name_linter step where any code that matches the xpath string for assignments, the only assignment that is pulled out is that for Z, both the argument-names x and b.a.z are ignored.

@jimhester

Copy link
Copy Markdown
Member Author

Oh yeah, formal arguments are not normal assignments, so likely we would need to write a new xpath query to capture them.

@russHyde

Copy link
Copy Markdown
Collaborator

Cheers. (Without previously working with xpath syntax) I extended the xpath string as follows:

    xpath <- paste0(                                                                                                      
      # Left hand assignments                                                                                             
      "//expr[SYMBOL or STR_CONST][following-sibling::LEFT_ASSIGN or following-sibling::EQ_ASSIGN]/*",                    
      # Or                                                                                                                
      " | ",                                                                                                                                                                                                                             
      # Right hand assignments                                                                                            
      "//expr[SYMBOL or STR_CONST][preceding-sibling::RIGHT_ASSIGN]/*",                                                                                                                                                                             
      # Or                                                                                                                
      " | ",                                                                                                                                                                                                                                        
      # Formal argument names                                                                                             
      "//SYMBOL_FORMALS"                                                                                                  
    )

This seems to capture the formals and any variable assignments. And, with the other changes (above) that ensure each variable matches at least one of the named styles (rather than all of them), all the existing unit tests now pass (I also added a ... argument to make sure this isn't caught when linting against the SYMBOL_FORMALS).

Forgive my git-ignorance, am I allowed to make a pull request to jimhester/lintr:name_performance from my fork of lintr, I've only ever PR'd against master (or within repos that I own)?

@jimhester

Copy link
Copy Markdown
Member Author

Yes, you can make a PR against my PR. But actually as a full contributor to lintr I think you may be able to make commits directly to it. There are some usethis functions to make this simpler.

# fetch the PR code to a local branch
usethis::pr_fetch(236)

# make your changes and commit

# push the changes back to the PR
usethis::pr_push()

@russHyde

russHyde commented Aug 23, 2019 •

Copy link
Copy Markdown
Collaborator

Thanks Jim, usethis does an awful lot of stuff that I didn't know about.

I ended up making changes in a separate PR off this branch in #398 . If it makes it easier, I can add them directly into this PR

* lint formals and ensure names match >= 1 style

Previous xml-based version of object_name_linter:

- required all names to match every one of the requested
  styles

- disregarded names of formals in newly-defined functions

Hence:

- added extra xpath clause to catch SYMBOL_FORMALS

- used or-reduction to ensure each name matches at least one
style.

Also:

- since multiple styles are allowed, the lint message is now
  like "Variable and function name style should be style_1,
  style_2 or style_3".

- tests for `object_name_linter` and lint message for
  `object_name_linter_old` were changed to match this
  format.

- added `...` argument to a unit test to ensure that
  `object_name_linter` does not flag dots.

* change docs to reflect use of >= 1 style

Added UTF-8 encoding to DESCRIPTION to get roxygen to
compile the docs
@russHyde

Copy link
Copy Markdown
Collaborator

Hi @jimhester , I've added my changes onto this PR now.

@jimhester

Copy link
Copy Markdown
Member Author

Ok I have fixed the conflicts, @russHyde if this looks good to you now you can approve this PR and merge it.

@russHyde

Copy link
Copy Markdown
Collaborator

Brilliant. Merging now.

@russHyde
russHyde merged commit dfe00be into master Aug 23, 2019
@AshesITR
AshesITR deleted the name_performance branch December 6, 2020 11:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Major speed deprecation with new object linters

4 participants