yihui / formatR

Format R Code Automatically
https://yihui.org/formatr/
255 stars 52 forks source link

Fails on comment between `if` condition an opening brace #48

Closed kenahoo closed 9 years ago

kenahoo commented 9 years ago

The following error happens:

> tidy_source(text="for(i in 1:10) #Loop to ten\n{print(i)}", comment=TRUE)
Error in base::parse(text = code, srcfile = NULL) : 
  1:21: unexpected SPECIAL
1: for ( i in 1 : 10 ) %InLiNe_IdEnTiFiEr%
                        ^

It looks like you stick %InLiNe_IdEnTiFiEr% into the source where the comment was, in order to stick the comment back in later, but it's not allowed there so the parser blows up.

Ideally, this text would be transformed into "for (i in 1:10) { #Loop to ten\n print(i)\n}", which involves transposing the opening brace and the comment. Sounds like it might be tricky though?

yihui commented 9 years ago

Please see Section 6: http://yihui.name/formatR/

kenahoo commented 9 years ago

Bummer - in many cases I don't actually control the code I'm trying to format, and the fact that it's doing this non-recommended stuff is really the reason we're using an automatic formatter.

Would you consider adding a function that attempts to clean up situations like these (many of them detectable with pretty good accuracy using a regex) before we run tidy_source?

kenahoo commented 9 years ago

Incidentally, the same problem happens for comments explaining the steps in a dplyr or magrittr chain, right? To me that often seems like good practice, not something to be avoided.

> code <- '
df %>% #foo
bar() %>% #bar
baz()'
> tidy_source(text=code, comment=TRUE, width=60, output=F)$text.tidy
Error in base::parse(text = code, srcfile = NULL) : 
  1:8: unexpected SPECIAL
1: df %>% %InLiNe_IdEnTiFiEr%
           ^
yihui commented 9 years ago

Sorry I don't know how to deal with such cases. If you can come up with a solution, pull requests are welcome! :)

Personally I don't like the style of injecting comments after a line that is not a complete R expression. If any line of code needs that level of detailed comments, I'd consider rewriting it to avoid heavy comments.

kenahoo commented 9 years ago

The only thing I can think of is a whole new parsing approach, not based on core::parse. I've always wanted an excuse to do a project with Marpa (https://jeffreykegler.github.io/Marpa-web-site/), maybe now I will. =)

yihui commented 9 years ago

Okay, good luck!